package com.bf.electroplating.service.impl;

import com.alibaba.excel.util.StringUtils;
import com.alibaba.fastjson.JSONArray;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.bf.electroplating.mapper.CompanyDeviceRelationMapper;
import com.bf.electroplating.mapper.EnterpriseOutfallValveMapper;
import com.bf.electroplating.mapper.SewagePlantManualDetectionMapper;
import com.bf.electroplating.pojo.dto.frontPage.*;
import com.bf.electroplating.pojo.entity.*;
import com.bf.electroplating.pojo.enums.DicTypeEnums;
import com.bf.electroplating.pojo.enums.IndustryTypeEnum;
import com.bf.electroplating.pojo.enums.OutfallEnums;
import com.bf.electroplating.pojo.vo.ParkSumaryVO;
import com.bf.electroplating.pojo.vo.SelectVo;
import com.bf.electroplating.pojo.vo.home.*;
import com.bf.electroplating.pojo.vo.inflowManagement.InflowManagementVO;
import com.bf.electroplating.pojo.vo.wasteGasMonitoringVO.WasteGasMonitoringLogVO;
import com.bf.electroplating.service.*;
import com.bf.electroplating.service.ICompanyDeviceService;
import com.bf.electroplating.service.IExhaustGasWarningConfigService;
import com.github.xiaoymin.knife4j.core.util.CollectionUtils;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.time.Duration;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 前端首页数据服务实现类
 */
@Slf4j
@Service
public class FrontHomeDataServiceImpl implements IFrontHomeDataService {

    @Autowired
    private ComCompanyService comCompanyService;

    @Autowired
    private ComProductionService comProductionService;

    @Autowired
    private ComWorkshopService comWorkshopService;

    @Autowired
    private ControlProblemFindingService controlProblemFindingService;

    @Autowired
    private ComEnvironmentallyFacilityService comEnvironmentallyFacilityService;

    @Autowired
    private ICompanyDeviceService companyDeviceService;
    @Resource
    private ICompanyDeviceRelationService companyDeviceRelationService;
    @Resource
    private SewagePlantManualDetectionMapper sewagePlantManualDetectionMapper;

    @Autowired
    private ICompanyDeviceStatusService companyDeviceStatusService;

    @Autowired
    private IWorkshopMonitoringPointService workshopMonitoringPointService;

    @Autowired
    private ISewageWarningConfigService sewageWarningConfigService;

    @Autowired
    private IInflowManagementService inflowManagementService;

    @Autowired
    private IWasteGasMonitoringService wasteGasMonitoringService;
    @Resource
    private IRainfallOutletSiteService rainfallOutletSiteService;
    @Resource
    private IExhaustGasWarningConfigService exhaustGasWarningConfigService;
    @Resource
    private ComExtraWorkshopService comExtraWorkshopService;

    @Autowired
    private IWasteGasMonitoringLogService wasteGasMonitoringLogService;

    @Autowired
    private IRainfallOutletWeatherDataService rainfallOutletWeatherDataService;

    @Autowired
    private IRainfallOutletMonitoringService rainfallOutletMonitoringService;

    @Autowired
    private IRainfallOutletSuspectedDischargeService rainfallOutletSuspectedDischargeService;

    @Autowired
    private ISewagePlantManualDetectionService sewagePlantManualDetectionService;
    @Resource
    private ISewagePlantWastewaterTypeService sewagePlantWastewaterTypeService;
    @Resource
    private IFrontEnterpriseService frontEnterpriseService;

    @Resource
    private PubParamDictionaryService pubParamDictionaryService;
    @Autowired
    private IWarningService iWarningService;
    @Resource
    private EnterpriseOutfallValveMapper enterpriseOutfallValveMapper;
    @Autowired
    private CompanyDeviceRelationMapper companyDeviceRelationMapper;
    @Resource
    private IParkOutletMonitoringService parkOutletMonitoringService;
    @Resource
    private IParkOutletMonitoringLogService parkOutletMonitoringLogService;
    @Resource
    private IWarningService warningService;
    @Resource
    private ISiteMonthlyStatisticsService siteMonthlyStatisticsService;

    @Override
    public ComplianceDataVO getComplianceData(String companyId) {
        ComplianceDataVO complianceData = new ComplianceDataVO();
        LambdaQueryWrapper<ControlProblemFinding> controlProblemFindingLambdaQueryWrapper = new LambdaQueryWrapper<>();
        LambdaQueryWrapper<ComWorkshop> comWorkshopLambdaQueryWrapper = new LambdaQueryWrapper<>();
        LambdaQueryWrapper<ComProduction> comProductionLambdaQueryWrapper = new LambdaQueryWrapper<>();
        if(!StringUtils.isEmpty(companyId)){
            controlProblemFindingLambdaQueryWrapper.eq(ControlProblemFinding::getCompanyId,companyId);
            comWorkshopLambdaQueryWrapper.eq(ComWorkshop::getCompanyId,companyId);
            comProductionLambdaQueryWrapper.eq(ComProduction::getCompanyId,companyId);
        }
        List<ComProduction> comProductions=comProductionService.list(comProductionLambdaQueryWrapper);
        complianceData.setQuestionCount((int)controlProblemFindingService.count(controlProblemFindingLambdaQueryWrapper));
        complianceData.setLineAllCount((int)comProductions.stream().filter(i->i.getApprovedLineCount()!=null).map(ComProduction::getApprovedLineCount).reduce(0, Integer::sum));
        complianceData.setLineHaveCount((int)comProductions.stream().filter(i->i.getEnterpriseProductionLineCou()!=null).map(ComProduction::getEnterpriseProductionLineCou).reduce(0, Integer::sum));
        return complianceData;
    }

    @Override
    public PowerMonitoringDataVO getPowerMonitoringData() {
        PowerMonitoringDataVO powerData = new PowerMonitoringDataVO();
        
        // 生产设施用电量监控
        List<ComCompany> companies = comCompanyService.list();

        // 废气处理设施用电量监控
        List<ComEnvironmentallyFacility> facilities = comEnvironmentallyFacilityService.list();
        Map<String, String> companyNameMap = companies.stream()
                .collect(Collectors.toMap(ComCompany::getId, ComCompany::getCompanyName));

        List<ExhaustGasPowerVO> exhaustGasPowerList = facilities.stream()
//                .limit(3)
                .map(facility -> {
                    ExhaustGasPowerVO vo = new ExhaustGasPowerVO();
                    vo.setCompanyName(companyNameMap.getOrDefault(facility.getCompanyId(), "未知企业"));
                    vo.setTotalPoints(2 + new Random().nextInt(3));
                    vo.setProductionPoints(1 + new Random().nextInt(2));
                    vo.setTreatmentPoints(1 + new Random().nextInt(2));
                    vo.setStatus(new Random().nextBoolean() ? "正常" : "异常");
                    return vo;
                })
                .collect(Collectors.toList());

        powerData.setExhaustGasFacilityPowerConsumption(exhaustGasPowerList);
        
        return powerData;
    }

    @Override
    public ExhaustGasControlDataVO getExhaustGasControlData(String companyId) {
        ExhaustGasControlDataVO exhaustGasData = new ExhaustGasControlDataVO();

        // 废气处理设施监控点位数据
        List<CompanyDevice> companyDevices = companyDeviceService.list();
        LambdaQueryWrapper<ComCompany> lambdaQueryWrapper=new LambdaQueryWrapper<>();
        if (!StringUtils.isEmpty(companyId)) {
            lambdaQueryWrapper.eq(ComCompany::getId,companyId);
        }
        List<ComCompany> companies = comCompanyService.list(lambdaQueryWrapper);
        Map<String, List<CompanyDevice>> deviceMap = companyDevices.stream()
                .collect(Collectors.groupingBy(CompanyDevice::getCompanyId));
        
        List<ExhaustGasFacilityVO> facilityList = companies.stream()
                .map(company -> {
                    ExhaustGasFacilityVO vo = new ExhaustGasFacilityVO();
                    vo.setCompanyName(company.getCompanyAbbreviation());
                    List<CompanyDevice> companyDevicesList = deviceMap.get(company.getExtraPlatformId());
                    vo.setTotalPoints(companyDevicesList!=null?companyDevicesList.size():0);
                    vo.setProductionPoints(companyDevicesList!=null?(int)companyDevicesList.stream().filter(i->"1".equals(i.getPlotName())).count():0);
                    vo.setTreatmentPoints(companyDevicesList!=null?(int)companyDevicesList.stream().filter(i->"2".equals(i.getPlotName())).count():0);
                    //todo 这里需要判断正常的逻辑
                    vo.setStatus( "正常" );
                    return vo;
                })
                .filter(i->i.getTotalPoints()!=0).collect(Collectors.toList());
        exhaustGasData.setFacilityMonitoringPoints(facilityList);
        
        // 废气处理设施状态统计
        Map<String, Object> statusStatistics = new HashMap<>();
        statusStatistics.put("total", facilityList.size());
        statusStatistics.put("normal", (int) facilityList.stream().filter(f -> "正常".equals(f.getStatus())).count());
        statusStatistics.put("abnormal", (int) facilityList.stream().filter(f -> "异常".equals(f.getStatus())).count());
        exhaustGasData.setStatusStatistics(statusStatistics);
        
        return exhaustGasData;
    }

    @Override
    public WaterQualityMonitoringDataVO getWaterQualityMonitoringData() {
        WaterQualityMonitoringDataVO waterQualityData = new WaterQualityMonitoringDataVO();

        List<WasteGasMonitoring> wasteGasMonitorings = wasteGasMonitoringService.list();
        Map<String, List<WasteGasMonitoring>> wasteGasMonitoringMap = wasteGasMonitorings.stream()
                .collect(Collectors.groupingBy(WasteGasMonitoring::getCompanyId));
        List<ExhaustGasWarningConfig> exhaustGasWarningConfigs = exhaustGasWarningConfigService.list();
        Map<String, List<ExhaustGasWarningConfig>> exhaustGasWarningConfigsMap = exhaustGasWarningConfigs.stream()
                .collect(Collectors.groupingBy(ExhaustGasWarningConfig::getCompanyId));

        Integer commonCount = 0;
        Integer warningCount = 0;

        // 对每家企业进行是否正常的判断
        for (String companyId : wasteGasMonitoringMap.keySet()) {
            List<WasteGasMonitoring> companyWasteGasList = wasteGasMonitoringMap.get(companyId);
            List<ExhaustGasWarningConfig> companyConfigList = exhaustGasWarningConfigsMap.getOrDefault(companyId, new ArrayList<>());
            
            // 判断该企业的废气监测数据是否正常
            boolean isCompanyNormal = isCompanyWasteGasNormal(companyWasteGasList, companyConfigList);
            
            if (isCompanyNormal) {
                commonCount++;
            } else {
                warningCount++;
            }
        }
        
        // 达标率统计
        Map<String, Object> complianceData = new HashMap<>();
        complianceData.put("value", commonCount);
        complianceData.put("name", "正常");
        Map<String, Object> complianceData1 = new HashMap<>();
        complianceData1.put("value", warningCount);
        complianceData1.put("name", "异常");

        waterQualityData.setComplianceStatistics(Arrays.asList(complianceData, complianceData1));
        
        return waterQualityData;
    }
    
    /**
     * 判断企业废气监测数据是否正常
     * @param wasteGasList 企业废气监测数据列表
     * @param configList 企业废气预警配置列表
     * @return true-正常，false-异常
     */
    private boolean isCompanyWasteGasNormal(List<WasteGasMonitoring> wasteGasList, List<ExhaustGasWarningConfig> configList) {
        if (wasteGasList == null || wasteGasList.isEmpty() || configList == null || configList.isEmpty()) {
            return true; // 没有数据或配置时认为正常
        }
        
        // 构建配置映射：deviceName + factorUnit -> ExhaustGasWarningConfig
        Map<String, ExhaustGasWarningConfig> configMap = new HashMap<>();
        for (ExhaustGasWarningConfig config : configList) {
            String key = config.getMonitoringFactor() + "_" + config.getFactorUnit();
            configMap.put(key, config);
        }
        
        // 检查每个废气监测数据是否在正常范围内
        for (WasteGasMonitoring wasteGas : wasteGasList) {
            String key = wasteGas.getDeviceName() + "_" + wasteGas.getMonitoringFactor();
            ExhaustGasWarningConfig config = configMap.get(key);
            if (config == null&&wasteGas.getDeviceName().contains("综合")) {
                 key = "综合废气1" + "_" + wasteGas.getMonitoringFactor();
                 config = configMap.get(key);
            }
            if (config == null) {
                log.warn("未找到对应的废气预警配置，设备名称: {}, 监测因子: {}", 
                        wasteGas.getDeviceName(), wasteGas.getMonitoringFactor());
                continue; // 没有配置时跳过该数据
            }
            
            // 判断监测值是否在正常范围内
            if (!isWasteGasValueNormal(wasteGas, config)) {
                log.info("企业废气监测数据异常，设备名称: {}, 监测因子: {}, 监测值: {}, 上限: {}, 下限: {}", 
                        wasteGas.getDeviceName(), wasteGas.getMonitoringFactor(), 
                        wasteGas.getOrpValue(), config.getUpperThreshold(), config.getLowerThreshold());
                return false; // 只要有一个数据异常，整个企业就认为异常
            }
        }
        
        return true; // 所有数据都正常
    }
    
    /**
     * 判断单个废气监测值是否正常
     * @param wasteGas 废气监测数据
     * @param config 废气预警配置
     * @return true-正常，false-异常
     */
    private boolean isWasteGasValueNormal(WasteGasMonitoring wasteGas, ExhaustGasWarningConfig config) {
        if (wasteGas.getOrpValue() == null&&wasteGas.getPhValue()==null) {
            return true; // 监测值为空时认为正常
        }
        
        BigDecimal monitoringValue = wasteGas.getPhValue();
        if (monitoringValue == null) {
            monitoringValue = wasteGas.getOrpValue();
        }
        BigDecimal upperLimit = config.getUpperThreshold();
        BigDecimal lowerLimit = config.getLowerThreshold();
        
        // 检查上限
        if (upperLimit != null && monitoringValue.compareTo(upperLimit) > 0) {
            return false;
        }
        
        // 检查下限
        if (lowerLimit != null && monitoringValue.compareTo(lowerLimit) < 0) {
            return false;
        }
        
        return true;
    }

    @Override
    public WarningManagementDataVO getWarningManagementData(String companyId) {
        WarningManagementDataVO warningData = new WarningManagementDataVO();
        String companyName=null;
        if (!StringUtils.isEmpty(companyId)) {
            ComCompany company=comCompanyService.getById(companyId);
            if (company!=null) {
                companyName=company.getCompanyName();
            }
        }
        LambdaQueryWrapper<Warning> lambdaQueryWrapper=new  LambdaQueryWrapper<Warning>()
                .orderByDesc(Warning::getWarningTime);
        if (!StringUtils.isEmpty(companyName)) {
            lambdaQueryWrapper.eq(Warning::getCompanyName, companyName);
        }
        lambdaQueryWrapper.ge(Warning::getWarningTime, LocalDate.now().withDayOfMonth(1));
        List<Warning> warnings=warningService.list(lambdaQueryWrapper);
        // 预警统计 - 模拟数据，实际应从预警表获取
        Map<String, Object> warningStatistics = new HashMap<>();
        warningStatistics.put("totalWarnings",warnings.size());
        warningStatistics.put("rainfallOutletWarnings",warnings.stream().filter(i->"2".equals(i.getWarningType())).count());
        warningStatistics.put("powerConsumptionWarnings",warnings.stream().filter(i->"1".equals(i.getWarningType())).count());
        warningStatistics.put("wastewaterDetectionWarnings",warnings.stream().filter(i->"3".equals(i.getWarningType())).count());
        warningData.setWarningStatistics(warningStatistics);
        // 预警列表 - 模拟数据
        List<WarningVO> warningList = new ArrayList<>();
        List<ComCompany> companies = comCompanyService.list();
        Map<String,ComCompany> map = companies.stream().collect(Collectors.toMap(ComCompany::getCompanyName,i->i));
        String[] warningTypes = {"废水检测预警", "用电量监控预警", "雨排口监控预警"};
        String[] statuses = {"异常", "未申报", "正常", "已申报"};
        
        for (int i = 0; i < 20 && i < warnings.size(); i++) {
            WarningVO warning = new WarningVO();
            BeanUtils.copyProperties(warnings.get(i),warning);
            Warning entity=warnings.get(i);
            ComCompany comCompany = map.get(warnings.get(i).getCompanyName());
            if (comCompany!=null){
                warning.setCompanyName(comCompany.getCompanyAbbreviation());
            }
            warning.setEventType(pubParamDictionaryService.getNameByModuleAndCode("YJLX",entity.getWarningType()));
            warning.setWarningIssue(entity.getWarningContent());
            warning.setWarningTime(entity.getWarningTime().format(DateTimeFormatter.ofPattern("yyyy-MM-dd")));
//            warning.setStatus(statuses[new Random().nextInt(statuses.length)]);
            warningList.add(warning);
        }
        warningData.setWarningList(warningList);
        
        return warningData;
    }

    @Override
    public EnterpriseMapDataVO getEnterpriseMapData(String companyId) {
        EnterpriseMapDataVO mapData = new EnterpriseMapDataVO();
        
        // 园区企业列表
        LambdaQueryWrapper<ComCompany> comCompanyLambdaQueryWrapper=new LambdaQueryWrapper<ComCompany>();
        if (!StringUtils.isEmpty(companyId)) {
            comCompanyLambdaQueryWrapper.eq(ComCompany::getId,companyId);
        }
        List<ComWorkshop> comWorkshops=comWorkshopService.list();
        List<ComProduction> comProductions=comProductionService.list();
        Map<String,List<ComProduction>> comProductionMap=comProductions.stream().collect(Collectors.groupingBy(ComProduction::getCompanyId));
        List<ComCompany> companies = comCompanyService.list(comCompanyLambdaQueryWrapper);
        List<EnterpriseMapVO> enterpriseList = companies.stream()
                .map(company -> {
                    EnterpriseMapVO vo = new EnterpriseMapVO();
                    vo.setCompanyId(company.getId());
                    vo.setCompanyName(company.getCompanyName());
                    vo.setLongitude(company.getLongitude());
                    vo.setCompanyAbbreviation(company.getCompanyAbbreviation());
                    vo.setIndustryType(IndustryTypeEnum.getDesc(company.getIndustryType()));
                    vo.setEnvironmentalOfficer(company.getEnvironmentalOfficer());
                    vo.setEnvironmentalOfficerPhone(company.getEnvironmentalOfficerPhone());
                    vo.setLatitude(company.getLatitude());
                    vo.setCodeStatus(new Random().nextBoolean() ? "绿码" : "黄码");
                    vo.setWorkshopCount((int)comWorkshops.stream().filter(i->company.getId().equals(i.getCompanyId())).count());
                    List<ComProduction> comProductionsList=comProductionMap.get(company.getId());
                    if (CollectionUtils.isEmpty(comProductionsList)) {
                        vo.setProductionLineCount(0);
                    }else {
                        vo.setProductionLineCount(comProductionsList.stream().filter(i->i.getEnterpriseProductionLineCou()!=null)
                                .map(ComProduction::getApprovedLineCount).reduce((a,b)->a+b).orElse(0));
                    }
                    vo.setRainOutLetOpenStatus(new Random().nextInt(1)+"");
                    vo.setPollutionDischargeInfo(getPollutionTypeByCode(company.getPollutionDischargeInfo()));
                    List<InflowManagementHomePageVO> enterpriseMapDataVOS=new ArrayList<>();
                    InflowManagementHomePageVO inflowManagementHomePageVO1=new InflowManagementHomePageVO();
                    inflowManagementHomePageVO1.setType("电导率");
                    inflowManagementHomePageVO1.setValue("4000");
                    InflowManagementHomePageVO inflowManagementHomePageVO2=new InflowManagementHomePageVO();
                    inflowManagementHomePageVO2.setType("综合塔1废气PH值");
                    inflowManagementHomePageVO2.setValue("4");
                    InflowManagementHomePageVO inflowManagementHomePageVO3=new InflowManagementHomePageVO();
                    inflowManagementHomePageVO3.setType("综合塔1废气ORP值");
                    inflowManagementHomePageVO3.setValue("2.5");
                    InflowManagementHomePageVO inflowManagementHomePageVO4=new InflowManagementHomePageVO();
                    inflowManagementHomePageVO4.setType("氰废气ORP");
                    inflowManagementHomePageVO4.setValue("12");
                    InflowManagementHomePageVO inflowManagementHomePageVO5=new InflowManagementHomePageVO();
                    inflowManagementHomePageVO5.setType("铬废气");
                    inflowManagementHomePageVO5.setValue("3.0");
                    enterpriseMapDataVOS.add(inflowManagementHomePageVO1);
                    enterpriseMapDataVOS.add(inflowManagementHomePageVO2);
                    enterpriseMapDataVOS.add(inflowManagementHomePageVO3);
                    enterpriseMapDataVOS.add(inflowManagementHomePageVO4);
                    enterpriseMapDataVOS.add(inflowManagementHomePageVO5);
                    vo.setInflowManagements(enterpriseMapDataVOS);
                    return vo;
                })
                .collect(Collectors.toList());
        mapData.setEnterpriseList(enterpriseList);
        
        // 园区统计信息
        List<EnterpriseDetailVO> enterpriseDetailVOS=Arrays.asList(new EnterpriseDetailVO("应急阀状态","1")
                ,new EnterpriseDetailVO("雨排口闸阀状态","1"),new EnterpriseDetailVO("雨水池液位计",new Random().nextInt(100)+"")
                ,new EnterpriseDetailVO("应急池液位计",new Random().nextInt(100)+"")
                ,new EnterpriseDetailVO("综合废气PH",new  Random().nextInt(100)+"")
        );

        mapData.setParkStatistics(enterpriseDetailVOS);
        
        return mapData;
    }
    private List<String> getPollutionTypeByCode(String pollutionDischargeInfo) {
        String[] split = pollutionDischargeInfo.split(",");
        List<String> pollutionTypeList = new ArrayList<>();
        if (split!=null && split.length>0) {
            for (int i = 0; i < split.length; i++) {
                String temp=split[i].trim();
                temp=pubParamDictionaryService.getNameByModuleAndCode(DicTypeEnums.PWLX.getCode(),temp);
                pollutionTypeList.add(temp);
            }
        }
        return pollutionTypeList;
    }

    @Override
    public WastewaterSeparationDataVO getWastewaterSeparationData() {
        WastewaterSeparationDataVO separationData = new WastewaterSeparationDataVO();

        // 企业废水检测数据
        Map<String, Object> enterpriseWastewaterData = new HashMap<>();
//        List<String> types=new ArrayList<>();
//        types.add("含铜");
//        types.add("含铬");
//        types.add("酸碱");
//        types.add("其他");
//        types.add("前期处理");
//        types.add("含氰");
//        types.add("化学镍");
//        types.add("电解");
        List<SelectVo> pubParamDictionaries=pubParamDictionaryService.getParamList("FSLX").getData();
        Map<String,String> waterTypeMap=pubParamDictionaries.stream().collect(Collectors.toMap(SelectVo::getName,SelectVo::getId));
        List<String> types=waterTypeMap.keySet().stream().map(i->i.replaceAll("废水","")).collect(Collectors.toList());
        List<SewageWarningConfig> sewageWarningConfigs=sewageWarningConfigService.list();
        List<InflowManagement> todayInflowManagements=inflowManagementService.list(new LambdaQueryWrapper<InflowManagement>()
                .eq(InflowManagement::getDetectionDate,LocalDate.now()));
        List<Integer> normalValues=new ArrayList<>();
        List<Integer> unnormalValues=new ArrayList<>();
        for (int i=0;i<types.size();i++) {
            String type=types.get(i);
            String typeCode=waterTypeMap.get(type+"废水");
            List<SewageWarningConfig> sewagePlantManualDetections=sewageWarningConfigs.stream().filter(j->typeCode.equals(j.getWasteWaterType()))
                    .collect(Collectors.toUnmodifiableList());
            List<InflowManagement> thisTypeData=todayInflowManagements.stream().filter(j->typeCode.equals(j.getWasteWaterType()))
                    .collect(Collectors.toUnmodifiableList());
          Integer normalValue=checkIsNormal(sewagePlantManualDetections,thisTypeData);
          Integer unnormalValue=sewagePlantManualDetections.size()-normalValue;
          normalValues.add(normalValue);
          unnormalValues.add(unnormalValue);
        }
        enterpriseWastewaterData.put("data", types);
        enterpriseWastewaterData.put("normalValues",normalValues);
        enterpriseWastewaterData.put("unnormalValues", unnormalValues);
        separationData.setEnterpriseWastewaterDetection(enterpriseWastewaterData);
        
        // 污水处理厂排污口在线监测数据
        Map<String, Object> treatmentPlantData = new HashMap<>();
        treatmentPlantData.put("selectedPlant", "新禹");
        treatmentPlantData.put("outletType", "预处理排口");

        LambdaQueryWrapper<EnterpriseOutfallValve> dataQuery = new LambdaQueryWrapper<>();
        dataQuery.eq(EnterpriseOutfallValve::getOutfallId, OutfallEnums.XY.getCode())
                .orderByDesc(EnterpriseOutfallValve::getMonitoringTime)
                .last("LIMIT 1");
        EnterpriseOutfallValve xyValue=enterpriseOutfallValveMapper.selectOne(dataQuery,false);
         dataQuery = new LambdaQueryWrapper<>();
        dataQuery.eq(EnterpriseOutfallValve::getOutfallId, OutfallEnums.BS.getCode())
                .orderByDesc(EnterpriseOutfallValve::getMonitoringTime)
                .last("LIMIT 1");
        EnterpriseOutfallValve bsValue=enterpriseOutfallValveMapper.selectOne(dataQuery,false);
        // 水质参数雷达图数据
            Map<String, Object> xyData = new LinkedHashMap<String, Object>() ;

        if (xyValue!=null) {
            xyData.put("cod", xyValue.getCodAvg());
            xyData.put("ph",xyValue.getPhAvg());
            xyData.put("flowRate",xyValue.getFlowRateAvg()!=null?xyValue.getFlowRateAvg():0);
            xyData.put("totalZinc",xyValue.getTotalZincAvg()!=null?xyValue.getTotalZincAvg():0);
            xyData.put("totalChromium",xyValue.getTotalChromiumAvg()!=null?xyValue.getTotalChromiumAvg():0);
            xyData.put("totalCopper",xyValue.getTotalCopperAvg()!=null?xyValue.getTotalCopperAvg():0);
            xyData.put("totalNitrogen", xyValue.getTotalNitrogenAvg()!=null?xyValue.getTotalNitrogenAvg():0);
            xyData.put("totalPhosphorus", xyValue.getTotalPhosphorusAvg()!=null?xyValue.getTotalPhosphorusAvg():0);
            xyData.put("ammoniaNitrogen", xyValue.getAmmoniaNitrogenAvg()!=null?xyValue.getAmmoniaNitrogenAvg():0);
        }
            treatmentPlantData.put("data1", xyData.keySet());
            treatmentPlantData.put("value1", xyData.values());
        Map<String, Object> bsData = new LinkedHashMap<>();
        if (bsValue!=null) {
            bsData.put("cod", bsValue.getCodAvg()!=null?bsValue.getCodAvg():0);
            bsData.put("ph",bsValue.getPhAvg()!=null?bsValue.getPhAvg():0);
            bsData.put("flowRate",bsValue.getFlowRateAvg()!=null?bsValue.getFlowRateAvg():0);
            bsData.put("totalZinc",bsValue.getTotalZincAvg()!=null?bsValue.getTotalZincAvg():0);
            bsData.put("totalChromium",bsValue.getTotalChromiumAvg()!=null?bsValue.getTotalChromiumAvg():0);
            bsData.put("totalCopper",bsValue.getTotalCopperAvg()!=null?bsValue.getTotalCopperAvg():0);
            bsData.put("totalNitrogen", bsValue.getTotalNitrogenAvg()!=null?bsValue.getTotalNitrogenAvg():0);
            bsData.put("totalPhosphorus", bsValue.getTotalPhosphorusAvg()!=null?bsValue.getTotalPhosphorusAvg():0);
            bsData.put("ammoniaNitrogen", bsValue.getAmmoniaNitrogenAvg()!=null?bsValue.getAmmoniaNitrogenAvg():0);
        }
        treatmentPlantData.put("data2", bsData.keySet());
        treatmentPlantData.put("value2", bsData.values());
        separationData.setTreatmentPlantMonitoring(treatmentPlantData);
        separationData.setRate("100");

        separationData.setTotalCount(getWastewaterTotalDetectionCount());
        return separationData;
    }

    private Integer getWastewaterTotalDetectionCount() {

        return  sewagePlantManualDetectionMapper.getWastewaterTotalDetectionCount();
    }

    @Override
    public RainfallOutletDataVO getRainfallOutletData(String id) {
        if (StringUtils.isEmpty(id)){
            id="1";
        }
        RainfallOutletDataVO rainfallData = new RainfallOutletDataVO();
        
        // 园区雨排口数据
        Map<String, Object> parkRainfallData = new LinkedHashMap<>();
        List<ParkOutletVO> parkOutlets = new ArrayList<>();
        
        // 从数据库获取园区排口监控数据
        List<ParkOutletMonitoring> parkOutletMonitorings = parkOutletMonitoringService.list(
                new LambdaQueryWrapper<ParkOutletMonitoring>()
                        .eq(ParkOutletMonitoring::getDelFlag, "0")
        );
        
        // 按排口名称分组
        Map<String, List<ParkOutletMonitoring>> outletGroups = parkOutletMonitorings.stream()
                .collect(Collectors.groupingBy(ParkOutletMonitoring::getOutletAbbreviation));

        for (Map.Entry<String, List<ParkOutletMonitoring>> entry : outletGroups.entrySet()) {
            String outletName = entry.getKey();
            List<ParkOutletMonitoring> outletData = entry.getValue();
            
            ParkOutletVO outlet = new ParkOutletVO();
            outlet.setId(outletName.substring(outletName.length()-1));
            outlet.setOutletName(outletName);
            
            // 获取最新的监测数据（用于后续可能的扩展）
            // ParkOutletMonitoring latestData = outletData.stream()
            //         .filter(data -> data.getMonitoringTime() != null)
            //         .max(Comparator.comparing(ParkOutletMonitoring::getMonitoringTime))
            //         .orElse(outletData.get(0));
            
            // 根据监测因子设置对应的数值
            for (ParkOutletMonitoring data : outletData) {
                String factorCode = data.getMonitoringFactorCode();
                if ("PH".equals(factorCode)) {
                    outlet.setPhValue(data.getValueNew() != null ? data.getValueNew().doubleValue() : 0.0);
                } else if ("DDL".equals(factorCode)) { // 电导率
                    outlet.setConductivity(data.getValueNew() != null ? data.getValueNew().doubleValue() : 0.0);
                }
            }
            
            // 设置阀门状态（这里可以根据实际业务逻辑设置）
            outlet.setValveStatus("开"); // 默认状态，可根据实际需求调整
            
            parkOutlets.add(outlet);
        }
        parkOutlets=parkOutlets.stream().sorted(Comparator.comparing(ParkOutletVO::getOutletName)).collect(Collectors.toList());
        parkRainfallData.put("outlets", parkOutlets);
        
        // 获取历史数据（最近24小时）
        LocalDateTime endTime = LocalDateTime.now();
        LocalDateTime startTime = endTime.minusHours(24);

        List<ParkOutletMonitoringLog> historicalData1 = parkOutletMonitoringLogService.list(
                new LambdaQueryWrapper<ParkOutletMonitoringLog>()
                        .between(ParkOutletMonitoringLog::getLogTime, startTime, endTime)
                        .eq(ParkOutletMonitoringLog::getOutletAbbreviation, "排口1")
                        .orderByAsc(ParkOutletMonitoringLog::getLogTime)
        );

        List<ParkOutletMonitoringLog> historicalData2 = parkOutletMonitoringLogService.list(
                new LambdaQueryWrapper<ParkOutletMonitoringLog>()
                        .between(ParkOutletMonitoringLog::getLogTime, startTime, endTime)
                        .eq(ParkOutletMonitoringLog::getOutletAbbreviation, "排口2")
                        .orderByAsc(ParkOutletMonitoringLog::getLogTime)
        );
        
        // 创建监测ID到监测因子编码的映射
        Map<String, String> monitoringIdToFactorCodeMap = parkOutletMonitorings.stream()
                .filter(i->i.getMonitoringFactorCode()!=null)
                .collect(Collectors.toMap(
                        ParkOutletMonitoring::getOutletId,
                        ParkOutletMonitoring::getMonitoringFactorCode,
                        (existing, replacement) -> existing // 如果有重复键，保留第一个
                ));
        
        // 按小时分组历史数据
        Map<Integer, List<ParkOutletMonitoringLog>> hourlyData1 = historicalData1.stream()
                .collect(Collectors.groupingBy(log -> log.getLogTime().getHour()));
        Map<Integer, List<ParkOutletMonitoringLog>> hourlyData2 = historicalData2.stream()
                .collect(Collectors.groupingBy(log -> log.getLogTime().getHour()));
        List<String> hours = new ArrayList<>();
        List<String> phs1 = new ArrayList<>();
        List<String> conductivity1 = new ArrayList<>();
        List<String> orp1 = new ArrayList<>();
        List<String> phs2 = new ArrayList<>();
        List<String> conductivity2 = new ArrayList<>();
        List<String> orp2 = new ArrayList<>();
        LocalDateTime now = LocalDateTime.now();
        // 生成24小时的数据
        for (int i = 0; i <= now.getHour(); i++) {
            hours.add(String.valueOf(i));
            
            List<ParkOutletMonitoringLog> hourData1 = hourlyData1.get(i);
            List<ParkOutletMonitoringLog> hourData2 = hourlyData2.get(i);

            // 获取排口1的数据 - 取节点值或最近值
            double phValue1 = getValueForHour(hourData1, "PH", monitoringIdToFactorCodeMap, i, historicalData1);
            double conductivityValue1 = getValueForHour(hourData1, "DDL", monitoringIdToFactorCodeMap, i, historicalData1);
            double orpValue1 = getValueForHour(hourData1, "ORP", monitoringIdToFactorCodeMap, i, historicalData1);
            
            phs1.add(String.format("%.2f", phValue1));
            conductivity1.add(String.format("%.2f", conductivityValue1));
            orp1.add(String.format("%.2f", orpValue1));

            // 获取排口2的数据 - 取节点值或最近值
            double phValue2 = getValueForHour(hourData2, "PH", monitoringIdToFactorCodeMap, i, historicalData2);
            double conductivityValue2 = getValueForHour(hourData2, "DDL", monitoringIdToFactorCodeMap, i, historicalData2);
            double orpValue2 = getValueForHour(hourData2, "ORP", monitoringIdToFactorCodeMap, i, historicalData2);
            
            phs2.add(String.format("%.2f", phValue2));
            conductivity2.add(String.format("%.2f", conductivityValue2));
            orp2.add(String.format("%.2f", orpValue2));
        }
        
        parkRainfallData.put("PH(排口1)", phs1);
        parkRainfallData.put("PH(排口2)", phs2);
        parkRainfallData.put("电导率(排口1)", conductivity1);
        parkRainfallData.put("电导率(排口2)", conductivity2);
        parkRainfallData.put("hours", hours);
        rainfallData.setParkRainfallOutlet(parkRainfallData);
        
        // 企业雨排口数据
        List<ComCompany> companies = comCompanyService.list(new LambdaQueryWrapper<ComCompany>()
                .isNotNull(ComCompany::getExtraSiteId));
        List<RainfallOutletSite> rainfallOutletSites=rainfallOutletSiteService.list();
        Map<Integer,RainfallOutletSite> rainfallOutletSiteMap=rainfallOutletSites.stream().collect(Collectors.toMap(RainfallOutletSite::getSiteId, i->i));
        List<EnterpriseOutletVO> enterpriseOutlets = companies.stream()
                .map(company -> {
                    EnterpriseOutletVO vo = new EnterpriseOutletVO();
                    vo.setId(company.getId());
                    vo.setCompanyName(company.getCompanyAbbreviation());
                    vo.setDeviceStatus( "正常");
                    RainfallOutletSite rainfallOutletSite=rainfallOutletSiteMap.get(company.getExtraSiteId());
                    RainfallOutletWeatherData rainfallOutletWeatherData=rainfallOutletWeatherDataService.getOne(
                            new LambdaQueryWrapper<RainfallOutletWeatherData>()
                                    .eq(RainfallOutletWeatherData::getSiteId,company.getExtraSiteId())
                                    .orderByDesc(RainfallOutletWeatherData::getDataTime),false
                    );
                    if (rainfallOutletSite!=null) {
                        vo.setBaselineValue(rainfallOutletSite.getBaselineValue()+"");
                    }else {
                        vo.setBaselineValue("/");
                    }
                    if (rainfallOutletWeatherData!=null) {
                        vo.setCurrentConductivity(rainfallOutletWeatherData.getFactorValue()+"");
                    }else {
                        vo.setCurrentConductivity("/");
                    }
                    if (rainfallOutletWeatherData!=null) {
                        vo.setRainfall(rainfallOutletWeatherData.getRainAmount()+"");
                    }else {
                        vo.setRainfall("/");
                    }
                    RainfallOutletMonitoring rainfallOutletMonitoring=rainfallOutletMonitoringService.getOne(
                            new LambdaQueryWrapper<RainfallOutletMonitoring>()
                                    .eq(RainfallOutletMonitoring::getExtraSiteId,company.getExtraSiteId())
                                    .eq(RainfallOutletMonitoring::getDeviceName,"雨排口阀门"),false
                    );
                    if (rainfallOutletMonitoring!=null) {
                        vo.setValveStatus("1".equals(rainfallOutletMonitoring.getRainOutletValveStatus())?"开":"关");
                    }else {
                        vo.setValveStatus("关");
                    }
                    return vo;
                })
                .collect(Collectors.toList());
        rainfallData.setEnterpriseRainfallOutlet(enterpriseOutlets);

        return rainfallData;
    }

    @Override
    public List<EnterpriseDeviceTreeVO> getEnterpriseDeviceTree(String companyId) {
        try {
            log.info("开始构建企业设备树");
            
            // 获取所有数据
            LambdaQueryWrapper<ComCompany> comCompanyLambdaQueryWrapper=new  LambdaQueryWrapper<>();
            if (!StringUtils.isEmpty(companyId)) {
                comCompanyLambdaQueryWrapper.eq(ComCompany::getId,companyId);
            }
            List<ComCompany> companies = comCompanyService.list(comCompanyLambdaQueryWrapper);
            List<ComExtraWorkshop> comExtraWorkshops = comExtraWorkshopService.list();
            List<WorkshopMonitoringPoint> workshopMonitoringPoints = workshopMonitoringPointService.list();
            List<CompanyDevice> companyDevices = companyDeviceService.list();

            // 按企业ID分组车间
            Map<String, List<ComExtraWorkshop>> workshopsByCompany = comExtraWorkshops.stream()
                    .collect(Collectors.groupingBy(ComExtraWorkshop::getCompanyId));


            // 监控点按园区ID分组监控点
            Map<String, List<WorkshopMonitoringPoint>> monitoringPointsByExtraWorkshop = workshopMonitoringPoints.stream()
                    .collect(Collectors.groupingBy(WorkshopMonitoringPoint::getWorkshopId));
            // 设备按监控点ID分组监控点
            Map<String, List<CompanyDevice>> companyMap = companyDevices.stream()
                    .collect(Collectors.groupingBy(CompanyDevice::getPlotId));
            // 构建企业节点（第一层）
            List<EnterpriseDeviceTreeVO> enterpriseNodes = companies.stream()
                    .filter(company -> workshopsByCompany.containsKey(company.getId()))
                    .map(company -> {
                        EnterpriseDeviceTreeVO companyNode = new EnterpriseDeviceTreeVO();
                        companyNode.setId(company.getId());
                        companyNode.setName(company.getCompanyName());
                        companyNode.setType("company");
                        companyNode.setCompanyId(company.getId());
                        companyNode.setCompanyName(company.getCompanyName());
                        companyNode.setExpanded(true);
                        companyNode.setLeaf(false);
                        
                        // 获取该企业的车间
                        List<ComExtraWorkshop> companyWorkshops = workshopsByCompany.getOrDefault(company.getId(), new ArrayList<>());
                        
                        // 构建车间节点（第二层）
                        List<EnterpriseDeviceTreeVO> workshopNodes = companyWorkshops.stream()
                                .map(workshop -> {
                                    EnterpriseDeviceTreeVO workshopNode = new EnterpriseDeviceTreeVO();
                                    workshopNode.setId(workshop.getId());
                                    workshopNode.setName(workshop.getWorkshopName());
                                    workshopNode.setType("workshop");
                                    workshopNode.setParentId(company.getId());
                                    workshopNode.setCompanyId(company.getId());
                                    workshopNode.setCompanyName(company.getCompanyName());
                                    workshopNode.setExpanded(true);
                                    workshopNode.setLeaf(false);
                                    
                                    // 获取该车间的园区
                                    List<WorkshopMonitoringPoint> workshopExtraWorkshops = monitoringPointsByExtraWorkshop.getOrDefault(workshop.getId(), new ArrayList<>());
                                    
                                    // 构建园区节点（第三层）
                                    List<EnterpriseDeviceTreeVO> extraWorkshopNodes = workshopExtraWorkshops.stream()
                                            .map(extraWorkshop -> {
                                                EnterpriseDeviceTreeVO extraWorkshopNode = new EnterpriseDeviceTreeVO();
                                                extraWorkshopNode.setId(extraWorkshop.getId());
                                                extraWorkshopNode.setName("1".equals(extraWorkshop.getPointName())?"生产监测点":"治理监测点");
                                                extraWorkshopNode.setType("point");
                                                extraWorkshopNode.setParentId(workshop.getId());
                                                extraWorkshopNode.setCompanyId(company.getId());
                                                extraWorkshopNode.setCompanyName(company.getCompanyName());
                                                extraWorkshopNode.setExpanded(true);
                                                extraWorkshopNode.setLeaf(false);
                                                
                                                // 获取该园区的监控点
                                                List<CompanyDevice> companyDeviceList = companyMap.getOrDefault(extraWorkshop.getId(), new ArrayList<>());
                                                
                                                // 构建监控点节点（第四层）
                                                List<EnterpriseDeviceTreeVO> monitoringPointNodes = companyDeviceList.stream()
                                                        .map(companyDevice -> {
                                                            EnterpriseDeviceTreeVO monitoringPointNode = new EnterpriseDeviceTreeVO();
                                                            monitoringPointNode.setName(companyDevice.getDeviceName());
                                                            monitoringPointNode.setId(companyDevice.getId());
                                                            monitoringPointNode.setType("monitoringPoint");
                                                            monitoringPointNode.setParentId(workshopNode.getId());
                                                            monitoringPointNode.setCompanyId(company.getId());
                                                            monitoringPointNode.setCompanyName(company.getCompanyName());
                                                            monitoringPointNode.setMonitoringPointId(extraWorkshop.getId());
                                                            monitoringPointNode.setExpanded(false);
                                                            monitoringPointNode.setLeaf(true);
                                                            monitoringPointNode.setChildren(new ArrayList<>());
                                                            
                                                            return monitoringPointNode;
                                                        })
                                                        .collect(Collectors.toList());
                                                
                                                extraWorkshopNode.setChildren(monitoringPointNodes);
                                                return extraWorkshopNode;
                                            })
                                            .collect(Collectors.toList());
                                    
                                    workshopNode.setChildren(extraWorkshopNodes);
                                    return workshopNode;
                                })
                                .collect(Collectors.toList());
                        
                        companyNode.setChildren(workshopNodes);
                        return companyNode;
                    })
                    .collect(Collectors.toList());
            
            log.info("企业设备树构建完成，共{}个企业节点", enterpriseNodes.size());
            return enterpriseNodes;
            
        } catch (Exception e) {
            log.error("构建企业设备树异常", e);
            return new ArrayList<>();
        }
    }

    @Override
    public MonitoringPointDetailVO getMonitoringPointDetail(String deviceId, String dataTime) {
        try {
            log.info("获取监测点详情数据，设备ID: {}, 数据时间: {}", deviceId, dataTime);
            
            MonitoringPointDetailVO detailVO = new MonitoringPointDetailVO();
            
            // 1. 获取设备信息
            CompanyDevice device = companyDeviceService.getById(deviceId);
            if (device == null) {
                log.warn("设备不存在，设备ID: {}", deviceId);
                return detailVO;
            }
            WorkshopMonitoringPoint workshopMonitoringPoint=workshopMonitoringPointService.getById(device.getPlotId());
            ComExtraWorkshop comWorkshop=null;
            if (workshopMonitoringPoint!=null)
            {
                comWorkshop=comExtraWorkshopService.getById(workshopMonitoringPoint.getWorkshopId());
            }
            // 2. 设置监测点基本信息
            detailVO.setMonitoringPointId(device.getPlotId());
            detailVO.setMonitoringPointName(device.getPlotName());
            detailVO.setCompanyId(device.getCompanyId());
            detailVO.setCompanyName(device.getCompanyName());
            detailVO.setWorkshopName(comWorkshop!=null?comWorkshop.getWorkshopName():""); // 使用监控点名称作为车间名称
            detailVO.setPlatingType(comWorkshop!=null?comWorkshop.getWorkshopPlatingType():"");
            detailVO.setPlatingType(""); // 需要从其他表获取
            detailVO.setStatus(device.getDeviceStatus());
            detailVO.setStatusName("1".equals(device.getDeviceStatus()) ? "正常" : "异常");
            detailVO.setMinThreshold(device.getStartStopThreshold());
            detailVO.setMaxThreshold(device.getStartStopThreshold()); // 使用同一个阈值
            detailVO.setLastUpdateTime(device.getUpdateTime().format(DateTimeFormatter.ofPattern("yyyy-MM-dd hh:mm:ss")));
            // 3. 设置监测点类型
            String deviceType = device.getDeviceType();
            if ("1".equals(deviceType)) {
                detailVO.setMonitoringPointType("1");
                detailVO.setMonitoringPointTypeName("生产监测点");
            } else if ("2".equals(deviceType)) {
                detailVO.setMonitoringPointType("2");
                detailVO.setMonitoringPointTypeName("治理监测点");
            }
            
            // 4. 获取运行数据（最新数据）
            MonitoringPointRunningDataVO runningData = getLatestRunningData(deviceId);
            detailVO.setRunningData(runningData);
                List<CompanyDeviceVO> companyDevices = getCompanyDevices(device.getCompanyId(), deviceId);
            detailVO.setCompanyDevices(companyDevices);
            // 5. 获取该公司所有其他设备列表

            // 6. 获取设备电流时间折线图数据（以天为单位）
            JSONArray chartData = getDeviceCurrentChartData(deviceId, dataTime,companyDevices);
            detailVO.setCurrentChartData(chartData);
            
            return detailVO;
            
        } catch (Exception e) {
            log.error("获取监测点详情数据异常", e);
            return new MonitoringPointDetailVO();
        }
    }
    
    /**
     * 获取最新运行数据
     */
    private MonitoringPointRunningDataVO getLatestRunningData(String deviceId) {
        // TODO: 实现获取最新运行数据的逻辑
        // 这里需要根据实际的设备数据表来查询最新数据
        MonitoringPointRunningDataVO runningData = new MonitoringPointRunningDataVO();
        // 设置默认值或从数据库查询
        CompanyDeviceStatus status=companyDeviceStatusService.getOne(new LambdaQueryWrapper<
                CompanyDeviceStatus>().eq(CompanyDeviceStatus::getDeviceId, deviceId)
                .orderByDesc(CompanyDeviceStatus::getCreateTime),false);
        if (status!=null){
            BeanUtils.copyProperties(status, runningData);
        }
        return runningData;
    }
    
    /**
     * 获取该公司所有其他设备列表
     */
    private List<CompanyDeviceVO> getCompanyDevices(String companyId, String excludeDeviceId) {
        try {
            List<CompanyDeviceRelation> companyDeviceRelations=companyDeviceRelationService.list(new LambdaQueryWrapper<CompanyDeviceRelation>()
                    .eq(CompanyDeviceRelation::getProductionDeviceId,excludeDeviceId));
            List<CompanyDevice> devices=new ArrayList<>();
            if(!CollectionUtils.isEmpty(companyDeviceRelations)){
                devices = companyDeviceService.list(new LambdaQueryWrapper<CompanyDevice>()
                        .in(CompanyDevice::getId,companyDeviceRelations.stream().map(CompanyDeviceRelation::getGovernanceDeviceId).collect(Collectors.toUnmodifiableList())));
            }
            if (!devices.stream().map(CompanyDevice::getId).collect(Collectors.toUnmodifiableList()).contains(excludeDeviceId)) {
                CompanyDevice companyDevice=companyDeviceService.getById(excludeDeviceId);
                devices.add(companyDevice);
            }
            // 查询该公司所有设备，排除当前设备

            return devices.stream().map(device -> {
                CompanyDeviceVO deviceVO = new CompanyDeviceVO();
                deviceVO.setDeviceId(device.getId());
                deviceVO.setDeviceName(device.getDeviceName());
                deviceVO.setDeviceType(device.getDeviceType());
                deviceVO.setDeviceTypeName("1".equals(device.getDeviceType()) ? "生产监测点" : "治理监测点");
                deviceVO.setStatus(device.getDeviceStatus());
                deviceVO.setStatusName("1".equals(device.getDeviceStatus()) ? "正常" : "异常");
                deviceVO.setMinThreshold(device.getStartStopThreshold());
                deviceVO.setDoorLimitTime(device.getDoorLimitTime());
                return deviceVO;
            }).collect(Collectors.toList());
            
        } catch (Exception e) {
            log.error("获取公司设备列表异常", e);
            return new ArrayList<>();
        }
    }
    
    /**
     * 获取设备电流时间折线图数据（以天为单位）
     */
    private JSONArray getDeviceCurrentChartData(String deviceId, String dataTime, List<CompanyDeviceVO> companyDevices) {
        try {
            // 1. 生成标准时间序列（00:00, 00:05, 00:10...直到当前时间）
            if (StringUtils.isBlank(dataTime)) {
                dataTime = LocalDate.now().toString();
            }

            // 2. 获取该公司所有设备
            CompanyDevice currentDevice = companyDeviceService.getById(deviceId);
            if (currentDevice == null) {
                return new JSONArray();
            }
            
//            List<CompanyDevice> companyDevices = companyDeviceService.list()
//                .stream()
//                .filter(device -> currentDevice.getCompanyId().equals(device.getCompanyId()))
//                .collect(Collectors.toList());
            
            // 3. 构建返回Map
            Map<String, List<String>> chartData = new HashMap<>();
            List<String>timeList=new ArrayList<>();
            // 4. 为每个设备获取电流数据
            CompanyDeviceStatus companyDeviceStatus=companyDeviceStatusService.getOne(new LambdaQueryWrapper<CompanyDeviceStatus>()
                    .eq(CompanyDeviceStatus::getDeviceId,currentDevice.getId())
                            .between(CompanyDeviceStatus::getCreateTime,parseDateTimeForDay(dataTime),parseDateTimeForDay(dataTime).toLocalDate().atTime(23,59,59))
                    .orderByDesc(CompanyDeviceStatus::getDataTime),false);
            if (companyDeviceStatus!=null&&!StringUtils.isEmpty(companyDeviceStatus.getChartList())) {
                JSONArray jsonArray = JSONArray.parseArray(companyDeviceStatus.getChartList());
                return jsonArray;
            }
//            for (CompanyDeviceVO device : companyDevices) {
//                CompanyDeviceStatus companyDeviceStatus=companyDeviceStatusService.getOne(new LambdaQueryWrapper<CompanyDeviceStatus>()
//                        .eq(CompanyDeviceStatus::getDeviceId,device.getDeviceId())
//                        .orderByDesc(CompanyDeviceStatus::getDataTime),false);
//                List<String> currentValues=new ArrayList<>();
//                if (companyDeviceStatus == null) {
//                    break;
//                }else {
//                    JSONArray jsonArray = JSONArray.parseArray(companyDeviceStatus.getChartList());
////                    if (CollectionUtils.isEmpty(jsonArray)) {
////                        break;
////                    }else {
////                        JSONArray jsonArray1= jsonArray.getJSONObject(0).getJSONArray("y");
////                        for (Object o : jsonArray1) {
////                            String value=o+"";
////                            currentValues.add(value);
////                        }
////                        JSONArray jsonArray2= jsonArray.getJSONObject(0).getJSONArray("x");
////                        for (Object o : jsonArray2) {
////                            String value=o+"";
////                            LocalDateTime localDateTime=LocalDateTime.parse(value,DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));
////                            timeList.add(localDateTime.getHour()+":"+localDateTime.getMinute()+":"+localDateTime.getSecond());
////                        }
////                        chartData.put("date", timeList);
////                        chartData.put(device.getDeviceName(), currentValues);
////                    }
                    return new JSONArray();
        } catch (Exception e) {
            log.error("获取设备电流时间折线图数据异常", e);
            return new JSONArray();
        }
    }
    
    /**
     * 生成标准时间序列
     */
    private List<String> generateTimeSequence(String dataTime) {
        List<String> timeList = new ArrayList<>();
        try {
            LocalDate date = LocalDate.parse(dataTime);
            LocalDateTime startTime = date.atStartOfDay();
            LocalDateTime currentTime = LocalDateTime.now();
            
            // 如果查询的是今天，则到当前时间；否则到23:55
            LocalDateTime endTime = date.equals(LocalDate.now()) ? 
                currentTime : date.atTime(23, 55);
            
            LocalDateTime time = startTime;
            while (!time.isAfter(endTime)) {
                timeList.add(time.format(DateTimeFormatter.ofPattern("HH:mm")));
                time = time.plusMinutes(5);
            }
            
        } catch (Exception e) {
            log.error("生成时间序列异常", e);
        }
        return timeList;
    }
    
    /**
     * 获取设备在指定时间点的电流值
     */
    private List<String> getDeviceCurrentValues(String deviceId, String dataTime, List<String> timeList) {
        List<String> currentValues = new ArrayList<>();
        
        try {
            // 查询该设备在指定日期的所有数据
            LocalDate date;
            if (!StringUtils.isEmpty(dataTime)) {
                date= LocalDate.parse(dataTime);
            }else {
                date = LocalDate.now();
            }
            LocalDateTime startTime = date.atStartOfDay();
            LocalDateTime endTime = LocalDateTime.now();
            
            // 查询设备数据（这里需要根据实际的设备数据表来查询）
            // 假设使用DeviceData表
//            List<CompanyDeviceStatus> deviceDataList = getDeviceDataByTimeRange(deviceId, startTime, endTime);
            CompanyDeviceStatus companyDeviceStatus=companyDeviceStatusService.getOne(new LambdaQueryWrapper<CompanyDeviceStatus>()
                    .eq(CompanyDeviceStatus::getDeviceId,deviceId)
                    .orderByDesc(CompanyDeviceStatus::getDataTime),false);
            if (companyDeviceStatus == null) {
                return currentValues;
            }else {
                JSONArray jsonArray = JSONArray.parseArray(companyDeviceStatus.getChartList());
                if (CollectionUtils.isEmpty(jsonArray)) {
                    return currentValues;
                }else {
                    JSONArray jsonArray1= jsonArray.getJSONObject(0).getJSONArray("y");
                    for (Object o : jsonArray1) {
                        String value=o+"";
                        currentValues.add(value);
                    }
                    return currentValues;
                }
            }
            // 为每个时间点找到对应的电流值
//                for (String timeStr : timeList) {
//                    String currentValue = findCurrentValueForTime(deviceDataList, timeStr);
//                    currentValues.add(currentValue);
//            }
            
        } catch (Exception e) {
            log.error("获取设备电流值异常", e);
            // 如果出错，返回默认值
            for (int i = 0; i < timeList.size(); i++) {
                currentValues.add("0");
            }
        }
        
        return currentValues;
    }
    
    /**
     * 根据时间范围查询设备数据
     */
    private List<CompanyDeviceStatus> getDeviceDataByTimeRange(String deviceId, LocalDateTime startTime, LocalDateTime endTime) {
        // TODO: 实现根据设备ID和时间范围查询设备数据的逻辑
        // 这里需要注入IDeviceDataService并调用相应方法
        // 示例代码：
         return companyDeviceStatusService.list(new LambdaQueryWrapper<CompanyDeviceStatus>()
             .eq(CompanyDeviceStatus::getDeviceId, deviceId)
             .between(CompanyDeviceStatus::getDataTime, startTime, endTime)
             .orderByAsc(CompanyDeviceStatus::getDataTime));
        
        // 临时返回空列表，实际应该从数据库查询
//        return new ArrayList<>();
    }
    
    /**
     * 为指定时间点找到对应的电流值
     */
    private String findCurrentValueForTime(List<CompanyDeviceStatus> deviceDataList, String timeStr) {
        if (deviceDataList == null || deviceDataList.isEmpty()) {
            return "0";
        }
        
        try {
            // 解析时间字符串
            String[] timeParts = timeStr.split(":");
            int hour = Integer.parseInt(timeParts[0]);
            int minute = Integer.parseInt(timeParts[1]);
            
            // 找到最接近的数据点
            CompanyDeviceStatus closestData = null;
            long minTimeDiff = Long.MAX_VALUE;
            
            for (CompanyDeviceStatus data : deviceDataList) {
                LocalDateTime dataTime = data.getDataTime();
                long timeDiff = Math.abs(dataTime.getHour() * 60 + dataTime.getMinute() - (hour * 60 + minute));
                
                if (timeDiff < minTimeDiff) {
                    minTimeDiff = timeDiff;
                    closestData = data;
                }
            }
            
            if (closestData != null && closestData.getCurrentA() != null) {
                return closestData.getCurrentA().toString();
            }
            
        } catch (Exception e) {
            log.error("查找电流值异常", e);
        }
        
        return "0";
    }

    @Override
    public MonitoringPointDataListVO getMonitoringPointDataList(String id, String startTime, String endTime, Integer currentPage, Integer pageSize) {
        try {
            log.info("获取监测点数据列表，设备ID: {}, 开始时间: {}, 结束时间: {}, 页码: {}, 每页大小: {}", 
                    id, startTime, endTime, currentPage, pageSize);
            
            MonitoringPointDataListVO result = new MonitoringPointDataListVO();
            
            // 1. 解析时间参数

            LocalDateTime startDateTime =null;

            LocalDateTime endDateTime =null;
            if (!StringUtils.isEmpty(startTime)) {
                startDateTime=parseDateTime(startTime);
            }
            if (!StringUtils.isEmpty(endTime)) {
                endDateTime=  parseDateTime(endTime);
            }

            // 2. 查询设备数据（分页）
            Page<CompanyDeviceStatus> deviceDataList = getDeviceDataList(id, startDateTime, endDateTime, currentPage, pageSize);
            
            // 3. 查询总记录数
//            Long total = getDeviceDataCount(id, startDateTime, endDateTime);
            
            // 4. 转换为VO
            List<MonitoringPointDataItemVO> dataItemList = deviceDataList.getRecords().stream()
                .map(this::convertToDataItemVO)
                .collect(Collectors.toList());
            CompanyDevice companyDevice=companyDeviceService.getById(id);
            dataItemList.forEach(i -> i.setDeviceName(companyDevice.getDeviceName()));

                // 5. 设置分页信息
            result.setDataList(dataItemList);
            result.setTotal(deviceDataList.getTotal());
            result.setCurrentPage((int)deviceDataList.getPages());
            result.setPageSize(pageSize);

            return result;
            
        } catch (Exception e) {
            log.error("获取监测点数据列表异常", e);
            return new MonitoringPointDataListVO();
        }
    }
    
    /**
     * 解析时间字符串
     */
    private LocalDateTime parseDateTime(String timeStr) {
//        if (StringUtils.isEmpty(timeStr)) {
//            return null;
//        }
        try {
            if (timeStr.contains(" ")) {
                // 格式：2025-09-01 00:00
                return LocalDateTime.parse(timeStr, DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));
            } else {
                // 格式：2025-09-01
                return LocalDate.parse(timeStr).atStartOfDay();
            }
        } catch (Exception e) {
            log.error("解析时间字符串异常: {}", timeStr, e);
            return LocalDateTime.now();
        }
    }

    /**
     * 解析时间字符串
     */
    private LocalDateTime parseDateTimeForDay(String timeStr) {

                return LocalDate.parse(timeStr).atStartOfDay();
    }
    
    /**
     * 查询设备数据列表（分页）
     */
    private Page<CompanyDeviceStatus> getDeviceDataList(String deviceId, LocalDateTime startTime, LocalDateTime endTime, Integer currentPage, Integer pageSize) {
        try {
            // TODO: 实现分页查询设备数据的逻辑
            // 这里需要注入IDeviceDataService并调用相应方法
            // 示例代码：
             Page<CompanyDeviceStatus> page = new Page<>(currentPage, pageSize);
            LambdaQueryWrapper<CompanyDeviceStatus> lambdaQueryWrapper=new LambdaQueryWrapper<CompanyDeviceStatus>()
                    .eq(CompanyDeviceStatus::getDeviceId, deviceId)
                    .orderByDesc(CompanyDeviceStatus::getDataTime);
            if (startTime != null&&endTime != null) {
                lambdaQueryWrapper .between(CompanyDeviceStatus::getDataTime, startTime, endTime.toLocalDate().atTime(23,59,59));
            }
              return companyDeviceStatusService.page(page,lambdaQueryWrapper);
            
            // 临时返回空列表，实际应该从数据库查询

        } catch (Exception e) {
            log.error("查询设备数据列表异常", e);
            return new Page<>();
        }
    }
    
    /**
     * 查询设备数据总数
     */
    private Long getDeviceDataCount(String deviceId, LocalDateTime startTime, LocalDateTime endTime) {
        try {
            // TODO: 实现查询设备数据总数的逻辑
            // 这里需要注入IDeviceDataService并调用相应方法
            // 示例代码：
            // return deviceDataService.count(new LambdaQueryWrapper<DeviceData>()
            //     .eq(DeviceData::getDeviceId, deviceId)
            //     .between(DeviceData::getDataTime, startTime, endTime));
            
            // 临时返回0，实际应该从数据库查询
            return 0L;
            
        } catch (Exception e) {
            log.error("查询设备数据总数异常", e);
            return 0L;
        }
    }
    
    /**
     * 转换为数据项VO
     */
    private MonitoringPointDataItemVO convertToDataItemVO(CompanyDeviceStatus deviceData) {
        MonitoringPointDataItemVO itemVO = new MonitoringPointDataItemVO();
        
        itemVO.setDataUpdateTime(deviceData.getDataTime().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")));
        itemVO.setDeviceName(deviceData.getDeviceCode()); // 使用设备编号作为设备名称
        itemVO.setVoltageA(deviceData.getVoltageA());
        itemVO.setVoltageB(deviceData.getVoltageB());
        itemVO.setVoltageC(deviceData.getVoltageC());
        itemVO.setCurrentA(deviceData.getCurrentA());
        itemVO.setCurrentB(deviceData.getCurrentB());
        itemVO.setCurrentC(deviceData.getCurrentC());
        itemVO.setActivePower(deviceData.getActivePower());
        itemVO.setReactivePower(deviceData.getReactivePower());
        itemVO.setPowerFactor(deviceData.getPowerFactor());
        
        return itemVO;
    }

    @Override
    public List<CompanyFactorTreeVO> getCompanyFactorTree() {
        try {
            log.info("开始构建企业检测因子树");
            
            // 1. 查询所有企业
            List<ComCompany> companies = comCompanyService.list();
            
            // 2. 查询所有检测因子配置
            List<SewageWarningConfig> configs = sewageWarningConfigService.list();
            
            // 3. 构建企业检测因子树
            List<CompanyFactorTreeVO> companyNodes = companies.stream()
                .map(company -> {
                    CompanyFactorTreeVO companyNode = new CompanyFactorTreeVO();
                    companyNode.setId(company.getId());
                    companyNode.setName(company.getCompanyName());
                    companyNode.setType("company");
                    companyNode.setParentId("0");
                    companyNode.setCompanyId(company.getId());
                    companyNode.setCompanyName(company.getCompanyName());
                    companyNode.setExpanded(false);
                    companyNode.setLeaf(false);
                    
                    // 获取该企业的检测因子
                    List<CompanyFactorTreeVO> factorNodes = getCompanyFactors(company.getId(), configs);
                    companyNode.setChildren(factorNodes);
                    
                    return companyNode;
                })
                .collect(Collectors.toList());
            
            log.info("企业检测因子树构建完成，共{}个企业节点", companyNodes.size());
            return companyNodes;
            
        } catch (Exception e) {
            log.error("构建企业检测因子树异常", e);
            return new ArrayList<>();
        }
    }
    
    /**
     * 获取企业的检测因子列表
     */
    private List<CompanyFactorTreeVO> getCompanyFactors(String companyId, List<SewageWarningConfig> configs) {
        List<CompanyFactorTreeVO> factors = new ArrayList<>();
        
        // 过滤出该企业的配置
        List<SewageWarningConfig> companyConfigs = configs.stream()
            .filter(config -> companyId.equals(config.getCompanyId()))
            .collect(Collectors.toList());
        
        // 为每个配置创建检测因子节点
        for (SewageWarningConfig config : companyConfigs) {
            // 六价铬检测因子
            if ("1".equals(config.getMonitorHexavalentChromium())) {
                CompanyFactorTreeVO factorNode = createFactorNode(
                    config.getId() + "_hexavalent_chromium",
                    "六价铬",
                    "hexavalent_chromium",
                    config.getHexavalentChromiumThreshold(),
                    companyId,
                    config.getWasteWaterType()
                );
                factors.add(factorNode);
            }
            
            // 总铬检测因子
            if ("1".equals(config.getMonitorTotalChromium())) {
                CompanyFactorTreeVO factorNode = createFactorNode(
                    config.getId() + "_total_chromium",
                    "总铬",
                    "total_chromium",
                    config.getTotalChromiumThreshold(),
                    companyId,
                    config.getWasteWaterType()
                );
                factors.add(factorNode);
            }
            
            // 总镍检测因子
            if ("1".equals(config.getMonitorTotalNickel())) {
                CompanyFactorTreeVO factorNode = createFactorNode(
                    config.getId() + "_total_nickel",
                    "总镍",
                    "total_nickel",
                    config.getTotalNickelThreshold(),
                    companyId,
                    config.getWasteWaterType()
                );
                factors.add(factorNode);
            }
        }
        
        return factors;
    }
    
    /**
     * 创建检测因子节点
     */
    private CompanyFactorTreeVO createFactorNode(String id, String name, String code, 
            BigDecimal threshold, String companyId, String wasteWaterType) {
        CompanyFactorTreeVO factorNode = new CompanyFactorTreeVO();
        factorNode.setId(id);
        factorNode.setName(name);
        factorNode.setType("factor");
        factorNode.setParentId(companyId);
        factorNode.setCompanyId(companyId);
        factorNode.setFactorName(name);
        factorNode.setFactorCode(code);
        factorNode.setIsMonitor("Y");
        factorNode.setThreshold(threshold);
        factorNode.setWasteWaterType(wasteWaterType);
        factorNode.setExpanded(false);
        factorNode.setLeaf(true);
        factorNode.setChildren(new ArrayList<>());
        
        return factorNode;
    }

    @Override
    public List<CompanyWastewaterTreeVO> getCompanyWastewaterTree() {
        try {
            log.info("开始构建企业废水类型树");
            
            // 1. 查询所有企业
            List<ComCompany> companies = comCompanyService.list();
            
            // 2. 查询所有废水类型配置
            List<SewageWarningConfig> configs = sewageWarningConfigService.list();
            
            // 3. 构建企业废水类型树，过滤掉没有子节点的公司
            List<CompanyWastewaterTreeVO> companyNodes = companies.stream()
                .map(company -> {
                    CompanyWastewaterTreeVO companyNode = new CompanyWastewaterTreeVO();
                    companyNode.setId(company.getId());
                    companyNode.setName(company.getCompanyName());
                    companyNode.setType("company");
                    companyNode.setParentId("0");
                    companyNode.setCompanyId(company.getId());
                    companyNode.setCompanyName(company.getCompanyName());
                    companyNode.setExpanded(false);
                    companyNode.setLeaf(false);
                    
                    // 获取该企业的废水类型
                    List<CompanyWastewaterTreeVO> wastewaterNodes = getCompanyWastewaterTypes(company.getId(), configs);
                    companyNode.setChildren(wastewaterNodes);
                    
                    return companyNode;
                })
                .filter(companyNode -> companyNode.getChildren() != null && !companyNode.getChildren().isEmpty())
                .collect(Collectors.toList());
            
            log.info("企业废水类型树构建完成，共{}个企业节点", companyNodes.size());
            return companyNodes;
            
        } catch (Exception e) {
            log.error("构建企业废水类型树异常", e);
            return new ArrayList<>();
        }
    }
    
    /**
     * 获取企业的废水类型列表
     */
    private List<CompanyWastewaterTreeVO> getCompanyWastewaterTypes(String companyId, List<SewageWarningConfig> configs) {
        List<CompanyWastewaterTreeVO> wastewaterTypes = new ArrayList<>();
        
        // 过滤出该企业的配置
        List<SewageWarningConfig> companyConfigs = configs.stream()
            .filter(config -> companyId.equals(config.getCompanyId()))
            .collect(Collectors.toList());
        
        // 为每个配置创建废水类型节点
        for (SewageWarningConfig config : companyConfigs) {
            CompanyWastewaterTreeVO wastewaterNode = createWastewaterNode(config);
            wastewaterTypes.add(wastewaterNode);
        }
        
        return wastewaterTypes;
    }
    
    /**
     * 创建废水类型节点
     */
    private CompanyWastewaterTreeVO createWastewaterNode(SewageWarningConfig config) {
        CompanyWastewaterTreeVO wastewaterNode = new CompanyWastewaterTreeVO();
        wastewaterNode.setId(config.getId());
        wastewaterNode.setType("wastewater");
        wastewaterNode.setParentId(config.getCompanyId());
        wastewaterNode.setCompanyId(config.getCompanyId());
        wastewaterNode.setWastewaterTypeCode(config.getWasteWaterType());
        List<SelectVo> pubParamDictionaries=pubParamDictionaryService.getParamList(DicTypeEnums.FSLX.getCode()).getData();
        Map<String,String> map=pubParamDictionaries.stream().collect(Collectors.toMap(SelectVo::getId,SelectVo::getName));
        wastewaterNode.setWastewaterTypeName(map.get(config.getWasteWaterType()));
        wastewaterNode.setName(wastewaterNode.getWastewaterTypeName());
        wastewaterNode.setConfigId(config.getId());
        wastewaterNode.setMonitorHexavalentChromium(config.getMonitorHexavalentChromium());
        wastewaterNode.setMonitorTotalChromium(config.getMonitorTotalChromium());
        wastewaterNode.setMonitorTotalNickel(config.getMonitorTotalNickel());
        wastewaterNode.setExpanded(false);
        wastewaterNode.setLeaf(true);
        wastewaterNode.setChildren(new ArrayList<>());
        return wastewaterNode;
    }

    @Override
    public PreDischargeDetailVO getPreDischargeDetail(String companyId,String waterId, String startTime, String endTime) {
        try {
            log.info("获取企业预排口运行详情，企业ID: {}, 开始时间: {}, 结束时间: {}", companyId, startTime, endTime);
            
            PreDischargeDetailVO detailVO = new PreDischargeDetailVO();
            
            // 1. 获取企业信息
            ComCompany company = comCompanyService.getById(companyId);
            if (company == null) {
                log.warn("企业不存在，企业ID: {}", companyId);
                return detailVO;
            }
            
            detailVO.setCompanyId(companyId);
            detailVO.setCompanyName(company.getCompanyName());
            detailVO.setStatus("正常");

            // 2. 解析时间参数
            LocalDateTime startDateTime = parseDateTime(startTime);
            LocalDateTime endDateTime = parseDateTime(endTime);
            
            // 3. 获取企业的预警配置
            LambdaQueryWrapper<SewageWarningConfig> lambdaQueryWrapper=new LambdaQueryWrapper<SewageWarningConfig>()
                    .eq(SewageWarningConfig::getCompanyId, companyId);
            if (!StringUtils.isEmpty(waterId)) {
                lambdaQueryWrapper.eq(SewageWarningConfig::getId,waterId);
            }
            List<SewageWarningConfig> configs = sewageWarningConfigService.list(
                    lambdaQueryWrapper
            );

            // 4. 获取企业的预排口历史数据
            List<InflowManagement> inflowData = inflowManagementService.list(
                new LambdaQueryWrapper<InflowManagement>()
                    .eq(InflowManagement::getCompanyId, companyId)
                    .between(InflowManagement::getDetectionDate, 
                        startDateTime.toLocalDate(), endDateTime.toLocalDate())
                    .orderByDesc(InflowManagement::getDetectionDate)
            );
            // 4. 获取企业的最新数据
            List<InflowManagement> newData = inflowManagementService.list(
                    new LambdaQueryWrapper<InflowManagement>()
                            .eq(InflowManagement::getCompanyId, companyId)
                            .orderByDesc(InflowManagement::getDetectionDate)
            );

            // 5. 构建运行数据列表
            List<PreDischargeRunningDataVO> runningDataList = buildRunningDataList(configs, newData);
            detailVO.setRunningDataList(runningDataList);
            if (!CollectionUtils.isEmpty(runningDataList)){
                detailVO.setLastUpdateTime(runningDataList.stream().filter(i->i.getTime()!=null).findFirst().map(PreDischargeRunningDataVO::getTime)
                        .orElse(LocalDate.now()).format(DateTimeFormatter.ofPattern("yyyy-MM-dd")));
            }
//            detailVO.setLastUpdateTime(LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd hh:mm:ss")));

            // 6. 构建时间序列图表数据
            Map<String, List<String>> chartData = buildChartData(configs, inflowData, startDateTime, endDateTime);
            detailVO.setChartData(chartData);
            
            return detailVO;
            
        } catch (Exception e) {
            log.error("获取企业预排口运行详情异常", e);
            return new PreDischargeDetailVO();
        }
    }

    @Override
    public Page<WasteGasMonitoringLogVO> getWasteGasList(String companyId, String itemId, String startTime, String endTime, Integer pageNum, Integer pageSize) {

        LambdaQueryWrapper<WasteGasMonitoringLog> lambdaQueryWrapper=new LambdaQueryWrapper<WasteGasMonitoringLog>();
        if (!StringUtils.isEmpty(startTime)&&!StringUtils.isEmpty(endTime)) {
            LocalDateTime startDateTime = parseDateTime(startTime);
            LocalDateTime endDateTime = parseDateTime(endTime);
            lambdaQueryWrapper.between(WasteGasMonitoringLog::getCreateTime,
                    startDateTime.toLocalDate(), endDateTime.toLocalDate());
        }
        if (!StringUtils.isEmpty(itemId)) {
            lambdaQueryWrapper.eq(WasteGasMonitoringLog::getMonitoringId,itemId);
        }
        lambdaQueryWrapper.orderByDesc(WasteGasMonitoringLog::getMonitoringTime);
        Page<WasteGasMonitoringLog> page=new Page<>(pageNum,pageSize);
        Page<WasteGasMonitoringLog> wasteGasMonitoringLogPage=  wasteGasMonitoringLogService.page(page,
                lambdaQueryWrapper
        );

        Page<WasteGasMonitoringLogVO> wasteGasMonitoringLogVOPage=new Page<>();
        List<WasteGasMonitoringLogVO> wasteGasMonitoringLogs=wasteGasMonitoringLogPage.getRecords().stream()
                .map(i->{
                    WasteGasMonitoringLogVO wasteGasMonitoringLogVO=new WasteGasMonitoringLogVO();
                    BeanUtils.copyProperties(i,wasteGasMonitoringLogVO);
                    wasteGasMonitoringLogVO.setMonitoringTime(i.getMonitoringTime().format(DateTimeFormatter.ofPattern("yyyy-MM-dd hh:mm:ss")));
                    wasteGasMonitoringLogVO.setStatus("1".equals(i.getStatus())?"在线":"离线");
                    return wasteGasMonitoringLogVO;
                }).collect(Collectors.toList());
        wasteGasMonitoringLogVOPage.setRecords(wasteGasMonitoringLogs);
        wasteGasMonitoringLogVOPage.setTotal(page.getTotal());
        return wasteGasMonitoringLogVOPage;
    }

    @Override
    public Page<InflowManagementVO> getPreDischargeList(String companyId, String waterId, String startTime, String endTime, Integer pageNum, Integer pageSize) {
        LambdaQueryWrapper<InflowManagement> inflowManagementLambdaQueryWrapper=new LambdaQueryWrapper<>();
        inflowManagementLambdaQueryWrapper.eq(InflowManagement::getCompanyId, companyId);
        // 2. 解析时间参数
        LocalDateTime startDateTime = parseDateTime(startTime);
        LocalDateTime endDateTime = parseDateTime(endTime);
        Page < InflowManagement > page = new Page <> ( pageNum , pageSize );

        LambdaQueryWrapper< InflowManagement > wrapper = new LambdaQueryWrapper <> ();

            wrapper.eq ( InflowManagement::getCompanyId , companyId );
            if (!StringUtils.isEmpty(waterId)){
                wrapper.eq ( InflowManagement::getWasteWaterType , waterId);
            }

            wrapper.between(InflowManagement::getDetectionDate,
                    startDateTime.toLocalDate(), endDateTime.toLocalDate());


        wrapper.orderByDesc ( InflowManagement::getCreateTime );

        Page < InflowManagement > resultPage = inflowManagementService.page ( page , wrapper );

        // 转换为VO
        Page < InflowManagementVO > voPage = new Page <> ();
        BeanUtils.copyProperties ( resultPage , voPage , "records" );
        List < InflowManagementVO > voList = new ArrayList<>();
        for ( InflowManagement entity : resultPage.getRecords () ) {
            InflowManagementVO vo = new InflowManagementVO ();
            BeanUtils.copyProperties ( entity , vo );
            vo.setStatus(getInflowStatus(entity));
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            vo.setFactorName(getFactorName(entity));
            vo.setWasteWaterType(pubParamDictionaryService.getNameByModuleAndCode("FSLX",vo.getWasteWaterType()));
            // 格式化日期
            vo.setCreateTime(sdf.format(entity.getCreateTime()));
            voList.add ( vo );
        }
        voPage.setRecords ( voList );
        return   voPage ;
    }

    private String getFactorName(InflowManagement entity) {
        String factorName = "";
        if ("1".equals(entity.getMonitorTotalNickel())){
            factorName+=",总镍";
        }
        if ("1".equals(entity.getMonitorTotalChromium())){
            factorName+=",总铬";
        }
        if ("1".equals(entity.getMonitorHexavalentChromium())){
            factorName+=",六价铬";
        }
        if (!StringUtils.isEmpty(factorName)){
            factorName=factorName.trim().substring(1,factorName.length());
        }
        return factorName;
    }

    private String getInflowStatus(InflowManagement vo) {
        String status = "正常";
        if ("1".equals(vo.getMonitorTotalNickel())&&vo.getTotalNickelThreshold().compareTo(vo.getTotalNickelValue()!=null?vo.getTotalNickelValue():new BigDecimal("0.0"))<0){
            status="异常";
        }
        if ("1".equals(vo.getMonitorHexavalentChromium())&&vo.getHexavalentChromiumThreshold().compareTo(vo.getHexavalentChromiumValue()!=null?vo.getHexavalentChromiumValue():new BigDecimal("0.0"))<0){
            status="异常";
        }
        if ("1".equals(vo.getMonitorTotalChromium())&&vo.getTotalChromiumThreshold().compareTo(vo.getTotalChromiumValue()!=null?vo.getHexavalentChromiumValue():new BigDecimal("0.0"))<0){
            status="异常";
        }
        return status;
    }

    /**
     * 构建运行数据列表
     */
    private List<PreDischargeRunningDataVO> buildRunningDataList(List<SewageWarningConfig> configs, 
            List<InflowManagement> inflowData) {
        List<PreDischargeRunningDataVO> runningDataList = new ArrayList<>();
        // 获取废水类型字典
        List<SelectVo> wastewaterTypes = pubParamDictionaryService.getParamList(DicTypeEnums.FSLX.getCode()).getData();
        Map<String, String> wastewaterTypeMap = wastewaterTypes.stream()
            .collect(Collectors.toMap(SelectVo::getId, SelectVo::getName));
        
        // 按废水类型分组处理
        Map<String, List<InflowManagement>> groupedData = inflowData.stream()
            .collect(Collectors.groupingBy(InflowManagement::getWasteWaterType));
        
        for (SewageWarningConfig config : configs) {
            PreDischargeRunningDataVO runningData = new PreDischargeRunningDataVO();
            
            // 设置基本信息
            runningData.setWasteWaterType(config.getWasteWaterType());
            runningData.setWasteWaterTypeName(wastewaterTypeMap.get(config.getWasteWaterType()));
            runningData.setMonitorHexavalentChromium(config.getMonitorHexavalentChromium());
            runningData.setMonitorTotalChromium(config.getMonitorTotalChromium());
            runningData.setMonitorTotalNickel(config.getMonitorTotalNickel());
            runningData.setHexavalentChromiumThreshold(config.getHexavalentChromiumThreshold());
            runningData.setTotalChromiumThreshold(config.getTotalChromiumThreshold());
            runningData.setTotalNickelThreshold(config.getTotalNickelThreshold());
            
            // 构建监测因子字符串
            StringBuilder factors = new StringBuilder();
            if ("1".equals(config.getMonitorHexavalentChromium())) {
                factors.append("六价铬 ");
            }
            if ("1".equals(config.getMonitorTotalChromium())) {
                factors.append("总铬 ");
            }
            if ("1".equals(config.getMonitorTotalNickel())) {
                factors.append("总镍 ");
            }
            runningData.setMonitoringFactors(factors.toString().trim());
            
            // 获取该废水类型的最新数据
            List<InflowManagement> typeData = groupedData.get(config.getWasteWaterType());
            if (typeData != null && !typeData.isEmpty()) {
                InflowManagement latestData = typeData.get(0); // 最新的数据
                runningData.setHexavalentChromiumValue(latestData.getHexavalentChromiumValue());
                runningData.setTotalChromiumValue(latestData.getTotalChromiumValue());
                runningData.setTotalNickelValue(latestData.getTotalNickelValue());
                runningData.setTime(latestData.getDetectionDate());
//                runningData.setStatus("在线");
            } else {
                runningData.setHexavalentChromiumValue(BigDecimal.ZERO);
                runningData.setTotalChromiumValue(BigDecimal.ZERO);
                runningData.setTotalNickelValue(BigDecimal.ZERO);
//                runningData.setStatus("离线");
            }
            runningDataList.add(runningData);
        }
        
        return runningDataList;
    }
    
    /**
     * 构建图表数据
     */
    private Map<String, List<String>> buildChartData(List<SewageWarningConfig> configs, 
            List<InflowManagement> inflowData, LocalDateTime startTime, LocalDateTime endTime) {
        Map<String, List<String>> chartData = new HashMap<>();
        
        // 生成时间序列
        List<String> timeList = generateTimeSequence(startTime.toLocalDate(), endTime.toLocalDate());
        chartData.put("date", timeList);
        
        // 获取废水类型字典
        List<SelectVo> wastewaterTypes = pubParamDictionaryService.getParamList(DicTypeEnums.FSLX.getCode()).getData();
        Map<String, String> wastewaterTypeMap = wastewaterTypes.stream()
            .collect(Collectors.toMap(SelectVo::getId, SelectVo::getName));
        
        // 按废水类型分组数据
        Map<String, Map<String, List<InflowManagement>>> groupedData = new HashMap<>();
        if (inflowData != null && !inflowData.isEmpty()) {
            groupedData = inflowData.stream()
                .collect(Collectors.groupingBy(
                    InflowManagement::getWasteWaterType,
                    Collectors.groupingBy(data -> data.getDetectionDate().toString())
                ));
        }
        
        // 获取所有可能的废水类型（优先从配置中获取，确保即使没有历史数据也能生成图表）
        Set<String> allWasteWaterTypes = new HashSet<>();
        
        // 首先从配置中获取废水类型
        if (configs != null && !configs.isEmpty()) {
            allWasteWaterTypes.addAll(configs.stream()
                .map(SewageWarningConfig::getWasteWaterType)
                .collect(Collectors.toSet()));
        }
        
        // 然后从历史数据中获取废水类型（补充配置中没有的）
        if (inflowData != null && !inflowData.isEmpty()) {
            allWasteWaterTypes.addAll(inflowData.stream()
                .map(InflowManagement::getWasteWaterType)
                .collect(Collectors.toSet()));
        }
        
        // 为每个废水类型和检测因子生成数据，即使没有数据也要生成
        for (String wasteWaterType : allWasteWaterTypes) {
            String wasteWaterTypeName = wastewaterTypeMap.get(wasteWaterType);
            if (wasteWaterTypeName == null) {
                wasteWaterTypeName = wasteWaterType; // 如果字典中没有，使用原值
            }
            
            Map<String, List<InflowManagement>> dateData = groupedData.getOrDefault(wasteWaterType, new HashMap<>());
            
            // 六价铬数据 - 确保每个时间点都有数据
            List<String> hexavalentChromiumData = timeList.stream()
                .map(date -> {
                    List<InflowManagement> dayData = dateData.get(date);
                    if (dayData != null && !dayData.isEmpty()) {
                        return dayData.get(0).getHexavalentChromiumValue() != null ? 
                            dayData.get(0).getHexavalentChromiumValue().toString() : "0";
                    }
                    return "0";
                })
                .collect(Collectors.toList());
            chartData.put(wasteWaterTypeName + "(六价铬)", hexavalentChromiumData);
            
            // 总铬数据 - 确保每个时间点都有数据
            List<String> totalChromiumData = timeList.stream()
                .map(date -> {
                    List<InflowManagement> dayData = dateData.get(date);
                    if (dayData != null && !dayData.isEmpty()) {
                        return dayData.get(0).getTotalChromiumValue() != null ? 
                            dayData.get(0).getTotalChromiumValue().toString() : "0";
                    }
                    return "0";
                })
                .collect(Collectors.toList());
            chartData.put(wasteWaterTypeName + "(总铬)", totalChromiumData);
            
            // 总镍数据 - 确保每个时间点都有数据
            List<String> totalNickelData = timeList.stream()
                .map(date -> {
                    List<InflowManagement> dayData = dateData.get(date);
                    if (dayData != null && !dayData.isEmpty()) {
                        return dayData.get(0).getTotalNickelValue() != null ? 
                            dayData.get(0).getTotalNickelValue().toString() : "0";
                    }
                    return "0";
                })
                .collect(Collectors.toList());
            chartData.put(wasteWaterTypeName + "(总镍)", totalNickelData);
        }
        
        // 如果没有历史数据，也要生成默认的废水类型数据
        if (allWasteWaterTypes.isEmpty()) {
            // 生成默认的废水类型数据，全部为0
            List<String> defaultData = timeList.stream().map(date -> "0").collect(Collectors.toList());
            chartData.put("默认废水类型(六价铬)", defaultData);
            chartData.put("默认废水类型(总铬)", defaultData);
            chartData.put("默认废水类型(总镍)", defaultData);
        }
        
        return chartData;
    }

    @Override
    public WasteGasDetailVO getWasteGasDetail(String companyId,String itemId, String startTime) {
        try {
            log.info("获取废气处理设施详情，企业ID: {}, 开始时间: {}, 结束时间: {}", companyId, startTime);

            WasteGasDetailVO detailVO = new WasteGasDetailVO();

            // 1. 获取企业信息
            ComCompany company = comCompanyService.getById(companyId);
            if (company == null) {
                log.warn("企业不存在，企业ID: {}", companyId);
                return detailVO;
            }

            detailVO.setCompanyId(companyId);
            detailVO.setCompanyName(company.getCompanyAbbreviation());
            List<WasteGasMonitoring> companyWasteGasList = wasteGasMonitoringService.list(
                    new LambdaQueryWrapper<WasteGasMonitoring>()
                            .eq(WasteGasMonitoring::getCompanyId, companyId)
            );
            List<ExhaustGasWarningConfig> companyConfigList = exhaustGasWarningConfigService.list( new LambdaQueryWrapper<ExhaustGasWarningConfig>()
                    .eq(ExhaustGasWarningConfig::getCompanyId, companyId));
            boolean isCompanyNormal = isCompanyWasteGasNormal(companyWasteGasList, companyConfigList);
            detailVO.setStatus(isCompanyNormal?"正常":"异常");
            detailVO.setLastUpdateTime(LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")));

            // 2. 解析时间参数
            LocalDateTime startDateTime = parseDateTimeForDay(startTime);
            LambdaQueryWrapper<WasteGasMonitoring> lambdaQueryWrapper= new LambdaQueryWrapper<WasteGasMonitoring>()
                    .eq(WasteGasMonitoring::getCompanyId, companyId);
            if (!StringUtils.isEmpty(itemId)){
                LambdaQueryWrapper<WasteGasMonitoring> myLam= new LambdaQueryWrapper<WasteGasMonitoring>()
                        .eq(WasteGasMonitoring::getCompanyId, companyId);
                myLam.eq(WasteGasMonitoring::getId,itemId);
                WasteGasMonitoring wasteGasFacilities = wasteGasMonitoringService.getOne(
                        myLam,false
                );
                lambdaQueryWrapper.eq(WasteGasMonitoring::getDeviceName, wasteGasFacilities.getDeviceName());
            }
            // 3. 获取企业的废气监测设施
            List<WasteGasMonitoring> wasteGasFacilities = wasteGasMonitoringService.list(
                    lambdaQueryWrapper
            );

            // 4. 获取企业的废气监测日志数据
            List<WasteGasMonitoringLog> logData = wasteGasMonitoringLogService.list(
                new LambdaQueryWrapper<WasteGasMonitoringLog>()
                    .eq(WasteGasMonitoringLog::getCompanyId, company.getId())
                    .between(WasteGasMonitoringLog::getMonitoringTime, startDateTime,startDateTime.toLocalDate().atTime(23,59,59))
                    .orderByDesc(WasteGasMonitoringLog::getMonitoringTime)
            );

            // 5. 构建运行数据列表
            List<WasteGasRunningDataVO> runningDataList = buildWasteGasRunningDataList(wasteGasFacilities, logData, companyConfigList);
            detailVO.setRunningDataList(runningDataList);
            // 6. 构建时间序列图表数据
            Map<String, List<String>> chartData = buildWasteGasChartData(wasteGasFacilities, logData, startDateTime,LocalDateTime.now());
            detailVO.setChartData(chartData);

            // 7. 设置MN码（取第一个设施的MN码）
            if (!wasteGasFacilities.isEmpty()) {
                detailVO.setMnCode(wasteGasFacilities.get(0).getMnCode());
            }

            return detailVO;

        } catch (Exception e) {
            log.error("获取废气处理设施详情异常", e);
            return new WasteGasDetailVO();
        }
    }

    @Override
    public List<CompanyWasteGasTreeVO> getCompanyWasteGasTree(String inCompanyId) {
        try {
            log.info("获取企业废气树数据");
            LambdaQueryWrapper<WasteGasMonitoring> lambdaQueryWrapper=new LambdaQueryWrapper<WasteGasMonitoring>();

            if (!StringUtils.isEmpty(inCompanyId)) {
                lambdaQueryWrapper.eq(WasteGasMonitoring::getCompanyId, inCompanyId);
            }
            // 1. 获取所有废气监测数据
            List<WasteGasMonitoring> wasteGasData = wasteGasMonitoringService.list(lambdaQueryWrapper);

            // 2. 按企业分组
            Map<String, List<WasteGasMonitoring>> companyGroupedData = wasteGasData.stream()
                .collect(Collectors.groupingBy(WasteGasMonitoring::getCompanyId));

            List<CompanyWasteGasTreeVO> treeList = new ArrayList<>();

            // 3. 构建企业节点
            for (Map.Entry<String, List<WasteGasMonitoring>> entry : companyGroupedData.entrySet()) {
                String companyId = entry.getKey();
                List<WasteGasMonitoring> companyWasteGasData = entry.getValue();

                // 获取企业信息
                ComCompany company = comCompanyService.getById(companyId);
                if (company == null) {
                    continue;
                }
                List<WasteGasMonitoring> wasteGasMonitorings = wasteGasMonitoringService.list();
                Map<String, List<WasteGasMonitoring>> wasteGasMonitoringMap = wasteGasMonitorings.stream()
                        .collect(Collectors.groupingBy(WasteGasMonitoring::getCompanyId));
                List<ExhaustGasWarningConfig> exhaustGasWarningConfigs = exhaustGasWarningConfigService.list();
                Map<String, List<ExhaustGasWarningConfig>> exhaustGasWarningConfigsMap = exhaustGasWarningConfigs.stream()
                        .collect(Collectors.groupingBy(ExhaustGasWarningConfig::getCompanyId));
                // 创建企业节点
                CompanyWasteGasTreeVO companyNode = new CompanyWasteGasTreeVO();
                companyNode.setId(companyId);
                companyNode.setName(company.getCompanyName());
                companyNode.setNodeType("company");
                companyNode.setParentId(null);
                companyNode.setCompanyId(companyId);
                companyNode.setCompanyName(company.getCompanyName());
                List<WasteGasMonitoring> companyWasteGasList = wasteGasMonitoringMap.get(companyId);
                List<ExhaustGasWarningConfig> companyConfigList = exhaustGasWarningConfigsMap.getOrDefault(companyId, new ArrayList<>());

                boolean isCompanyNormal = isCompanyWasteGasNormal(companyWasteGasList, companyConfigList);

                companyNode.setStatus(isCompanyNormal?"1":"0");

                // 4. 构建设备子节点
                List<CompanyWasteGasTreeVO> deviceNodes = new ArrayList<>();
                
                // 按设备名称分组
                Map<String, List<WasteGasMonitoring>> deviceGroupedData = companyWasteGasData.stream()
                    .collect(Collectors.groupingBy(WasteGasMonitoring::getDeviceName));

                for (Map.Entry<String, List<WasteGasMonitoring>> deviceEntry : deviceGroupedData.entrySet()) {
                    String deviceName = deviceEntry.getKey();
                    List<WasteGasMonitoring> deviceData = deviceEntry.getValue();

                    // 获取设备的最新数据
                    WasteGasMonitoring latestData = deviceData.stream()
                        .max(Comparator.comparing(WasteGasMonitoring::getMonitoringTime))
                        .orElse(deviceData.get(0));

                    // 创建设备节点
                    CompanyWasteGasTreeVO deviceNode = new CompanyWasteGasTreeVO();
                    deviceNode.setId(latestData.getId());
                    deviceNode.setName(deviceName);
                    deviceNode.setNodeType("device");
                    deviceNode.setParentId(companyId);
                    deviceNode.setCompanyId(companyId);
                    deviceNode.setCompanyName(company.getCompanyName());
                    deviceNode.setDeviceName(deviceName);
                    deviceNode.setMnCode(latestData.getMnCode());
                    deviceNode.setMonitoringFactor(latestData.getMonitoringFactor());

                    deviceNodes.add(deviceNode);
                }

                companyNode.setChildren(deviceNodes);
                treeList.add(companyNode);
            }

            return treeList;

        } catch (Exception e) {
            log.error("获取企业废气树数据异常", e);
            return new ArrayList<>();
        }
    }

    /**
     * 构建废气运行数据列表
     */
    private List<WasteGasRunningDataVO> buildWasteGasRunningDataList(List<WasteGasMonitoring> facilities, 
            List<WasteGasMonitoringLog> logData, List<ExhaustGasWarningConfig> configList) {
        List<WasteGasRunningDataVO> runningDataList = new ArrayList<>();
        
        // 构建配置映射：deviceName + monitoringFactor -> ExhaustGasWarningConfig
        // 注意：如果同一个设备+监测因子有多个配置（不同factorUnit），这里会取最后一个
        Map<String, ExhaustGasWarningConfig> configMap = new HashMap<>();
        if (configList != null && !configList.isEmpty()) {
            for (ExhaustGasWarningConfig config : configList) {
                // 使用 deviceName + monitoringFactor 作为key，与 isCompanyWasteGasNormal 中的查找逻辑保持一致
                String key = config.getMonitoringFactor() + "_" + config.getFactorUnit();
                configMap.put(key, config);
            }
        }
        
        for (WasteGasMonitoring facility : facilities) {
            WasteGasRunningDataVO runningData = new WasteGasRunningDataVO();
            runningData.setDeviceName(facility.getDeviceName());
            runningData.setMnCode(facility.getMnCode());
            runningData.setMonitoringFactor(facility.getMonitoringFactor());
            // 获取该设备的最新数据
            runningData.setPhValue(facility.getPhValue());
            runningData.setOrpValue(facility.getOrpValue());
            runningData.setStatus("在线");
            
            // 判断该条运行时数据是否正常
            String key = facility.getDeviceName() + "_" + facility.getMonitoringFactor();
            ExhaustGasWarningConfig config = configMap.get(key);
            if (config == null&&facility.getDeviceName().contains("综合")) {
                key = "综合废气1" + "_" + facility.getMonitoringFactor();
                config = configMap.get(key);
            }
            if (config != null) {
                // 使用 isWasteGasValueNormal 方法判断是否正常
                boolean isNormal = isWasteGasValueNormal(facility, config);
                if (runningData.getPhValue()!=null) {
                    runningData.setIsCommonPh(isNormal ? "0" : "1");
                }
                if (runningData.getOrpValue()!=null) {
                    runningData.setIsCommonOrp(isNormal ? "0" : "1");
                }
            } else {
                // 没有配置时，如果监测值为空则认为正常，否则需要根据实际情况判断
                // 这里暂时设置为正常，因为无法判断
                log.warn("未找到对应的废气预警配置，设备名称: {}, 监测因子: {}", 
                        facility.getDeviceName(), facility.getMonitoringFactor());
                if (runningData.getPhValue()!=null) {
                    runningData.setIsCommonPh("0");
                }
                if (runningData.getOrpValue()!=null) {
                    runningData.setIsCommonOrp("0");
                }
            }
            runningDataList.add(runningData);
        }
        
        return runningDataList;
    }

    /**
     * 构建废气图表数据
     */
    private Map<String, List<String>> buildWasteGasChartData(List<WasteGasMonitoring> facilities, 
            List<WasteGasMonitoringLog> logData, LocalDateTime startTime, LocalDateTime endTime) {
        Map<String, List<String>> chartData = new HashMap<>();
        if(!startTime.toLocalDate().equals(endTime.toLocalDate())) {
            endTime = startTime.toLocalDate().atTime(23,59,59);
        }
        // 生成时间序列（按小时）
        List<String> timeList = generateWasteGasTimeSequence(startTime, endTime);
        chartData.put("date", timeList);
        
        // 按设备名称分组历史数据
        Map<String, List<WasteGasMonitoringLog>> deviceGroupedData = new HashMap<>();
        if (logData != null && !logData.isEmpty()) {
            deviceGroupedData = logData.stream()
                .collect(Collectors.groupingBy(WasteGasMonitoringLog::getDeviceName));
        }
        
        // 为每个配置的废气设施生成PH和ORP数据，即使没有历史数据也要生成
        for (WasteGasMonitoring facility : facilities) {
            String deviceName = facility.getDeviceName();
            List<WasteGasMonitoringLog> deviceData = deviceGroupedData.getOrDefault(deviceName, new ArrayList<>());
            
            // PH数据 - 确保每个时间点都有数据
            List<String> phData = timeList.stream()
                .map(time -> {
                    List<WasteGasMonitoringLog> phList=deviceData.stream().filter(i->i.getPhValue()!=null).collect(Collectors.toList());
                    WasteGasMonitoringLog closestData = findClosestWasteGasDataForTime(phList, time);
                    return closestData != null && closestData.getPhValue() != null ? 
                        closestData.getPhValue().toString() : "0";
                })
                .collect(Collectors.toList());
            if (!(phData.stream().distinct().count()==1&&"0".equals(phData.get(0)))){
                chartData.put(deviceName + "(PH)", phData);
            }


            // ORP数据 - 确保每个时间点都有数据
            List<String> orpData = timeList.stream()
                .map(time -> {
                    List<WasteGasMonitoringLog> orpList=deviceData.stream().filter(i->i.getOrpValue()!=null).collect(Collectors.toList());
                    WasteGasMonitoringLog closestData = findClosestWasteGasDataForTime(orpList, time);
                    return closestData != null && closestData.getOrpValue() != null ? 
                        closestData.getOrpValue().toString() : "0";
                })
                .collect(Collectors.toList());
            if (!(orpData.stream().distinct().count()==1&&"0".equals(orpData.get(0)))) {
                chartData.put(deviceName + "(ORP)", orpData);
            }
            }
        
        // 如果没有配置的设施，也要生成默认数据

        
        return chartData;
    }

    /**
     * 生成废气时间序列（按小时）
     */
    private List<String> generateWasteGasTimeSequence(LocalDateTime startTime, LocalDateTime endTime) {
        List<String> timeList = new ArrayList<>();
        LocalDateTime currentTime = startTime;
        
        while (!currentTime.isAfter(endTime)) {
            timeList.add(currentTime.format(DateTimeFormatter.ofPattern("HH:mm")));
            currentTime = currentTime.plusHours(1);
        }
        
        return timeList;
    }

    /**
     * 查找最接近指定时间的废气数据
     */
    private WasteGasMonitoringLog findClosestWasteGasDataForTime(List<WasteGasMonitoringLog> deviceData, String timeStr) {
        if (deviceData.isEmpty()) {
            return null;
        }
        
        // 解析时间字符串
        LocalDateTime targetTime = LocalDateTime.parse(LocalDate.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd"))+" " + timeStr,
            DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm"));
        WasteGasMonitoringLog closest = null;
        long minDiff = Long.MAX_VALUE;
        
        for (WasteGasMonitoringLog data : deviceData) {
            long diff = Math.abs(Duration.between(data.getMonitoringTime(), targetTime).toMinutes());
            if (diff < minDiff) {
                minDiff = diff;
                closest = data;
            }
        }
        
        return closest;
    }
    
    /**
     * 生成时间序列（按天）
     */
    private List<String> generateTimeSequence(LocalDate startDate, LocalDate endDate) {
        List<String> timeList = new ArrayList<>();
        LocalDate currentDate = startDate;
        
        while (!currentDate.isAfter(endDate)) {
            timeList.add(currentDate.toString());
            currentDate = currentDate.plusDays(1);
        }
        
        return timeList;
    }

    @Override
    public Page<RainfallDataVO> getRainfallDataList(RainfallDataQueryDTO rainfallDataQueryDTO) {
        try {
            log.info("获取雨水数据列表，企业名称: {}, 开始时间: {}, 结束时间: {}", 
                    rainfallDataQueryDTO.getCompanyId(), rainfallDataQueryDTO.getStartTime(), rainfallDataQueryDTO.getEndTime());

            // 1. 解析时间参数
            LocalDateTime startDateTime = parseDateTime(rainfallDataQueryDTO.getStartTime());
            LocalDateTime endDateTime = parseDateTime(rainfallDataQueryDTO.getEndTime());

            // 2. 构建查询条件
            LambdaQueryWrapper<RainfallOutletWeatherData> queryWrapper = new LambdaQueryWrapper<>();
            
            // 企业名称条件
            if (!StringUtils.isEmpty(rainfallDataQueryDTO.getCompanyId())) {
                ComCompany company=comCompanyService.getById(rainfallDataQueryDTO.getCompanyId());
                if (company!=null&&company.getExtraSiteId()!=null) {
                    queryWrapper.eq(RainfallOutletWeatherData::getSiteId,company.getExtraSiteId());
                }
            }
            
            // 时间范围条件
            queryWrapper.between(RainfallOutletWeatherData::getDataTime, startDateTime, endDateTime.toLocalDate().atTime(23,59,59));
            
            // 站点ID条件
            if (rainfallDataQueryDTO.getSiteId() != null) {
                queryWrapper.eq(RainfallOutletWeatherData::getSiteId, rainfallDataQueryDTO.getSiteId());
            }
            
            // 天气条件
            if (!StringUtils.isEmpty(rainfallDataQueryDTO.getWeather())) {
                queryWrapper.like(RainfallOutletWeatherData::getWeatherName, rainfallDataQueryDTO.getWeather());
            }
            
            // 只查询有效数据

            // 按数据时间倒序排列
            queryWrapper.orderByDesc(RainfallOutletWeatherData::getDataTime);

            // 3. 分页查询
            Page<RainfallOutletWeatherData> page = new Page<>(rainfallDataQueryDTO.getPageNum(), rainfallDataQueryDTO.getPageSize());
            Page<RainfallOutletWeatherData> resultPage = rainfallOutletWeatherDataService.page(page, queryWrapper);

            // 4. 转换为VO
            Page<RainfallDataVO> voPage = new Page<>();
            BeanUtils.copyProperties(resultPage, voPage, "records");
            
            List<RainfallDataVO> voList = new ArrayList<>();
            for (int i = 0; i < resultPage.getRecords().size(); i++) {
                RainfallOutletWeatherData entity = resultPage.getRecords().get(i);
                RainfallDataVO vo = new RainfallDataVO();
                
                // 设置序号（从当前页开始计算）
                vo.setSerialNumber((rainfallDataQueryDTO.getPageNum() - 1) * rainfallDataQueryDTO.getPageSize() + i + 1);
                
                // 复制基本属性
                BeanUtils.copyProperties(entity, vo);
                
                // 格式化数据更新时间
                if (entity.getDataTime() != null) {
                    vo.setDataUpdateTime(entity.getDataTime().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm")));
                }
                
                // 设置电导率（使用因子值作为电导率）
                vo.setConductivity(entity.getFactorValue());
                
                voList.add(vo);
            }
            
            voPage.setRecords(voList);
            return voPage;

        } catch (Exception e) {
            log.error("获取雨水数据列表异常", e);
            return new Page<>();
        }
    }

    @Override
    public Page<MonthlyStatsVO> getMonthlyStatsList(MonthlyStatsQueryDTO monthlyStatsQueryDTO) {
        try {
            log.info("获取月度数据统计列表，企业ID: {}, 开始时间: {}, 结束时间: {}", 
                    monthlyStatsQueryDTO.getCompanyId(), monthlyStatsQueryDTO.getStartTime(), monthlyStatsQueryDTO.getEndTime());

            // 1. 解析时间参数
            LocalDateTime startDateTime = parseDateTime(monthlyStatsQueryDTO.getStartTime());
            LocalDateTime endDateTime = parseDateTime(monthlyStatsQueryDTO.getEndTime());

            // 2. 构建查询条件
            LambdaQueryWrapper<SiteMonthlyStatistics> queryWrapper = new LambdaQueryWrapper<>();
            
            // 企业ID条件
            if (!StringUtils.isEmpty(monthlyStatsQueryDTO.getCompanyId())) {
                ComCompany company=comCompanyService.getById(monthlyStatsQueryDTO.getCompanyId());
                if (company!=null&&company.getExtraSiteId()!=null) {
                    queryWrapper.eq(SiteMonthlyStatistics::getSiteId,company.getExtraSiteId());
                }
            }


            
            // 时间范围条件
            queryWrapper.between(SiteMonthlyStatistics::getVDate, startDateTime, endDateTime);
            
            // 按监测时间倒序排列
            queryWrapper.orderByDesc(SiteMonthlyStatistics::getVDate);

            // 3. 分页查询
            Page<SiteMonthlyStatistics> page = new Page<>(monthlyStatsQueryDTO.getPageNum(), monthlyStatsQueryDTO.getPageSize());
            Page<SiteMonthlyStatistics> resultPage = siteMonthlyStatisticsService.page(page, queryWrapper);

            // 4. 转换为VO
            Page<MonthlyStatsVO> voPage = new Page<>();
            BeanUtils.copyProperties(resultPage, voPage, "records");
            
            List<MonthlyStatsVO> voList = new ArrayList<>();
            for (int i = 0; i < resultPage.getRecords().size(); i++) {
                SiteMonthlyStatistics entity = resultPage.getRecords().get(i);
                MonthlyStatsVO vo = new MonthlyStatsVO();
                
                // 设置序号（从当前页开始计算）
                vo.setSerialNumber((monthlyStatsQueryDTO.getPageNum() - 1) * monthlyStatsQueryDTO.getPageSize() + i + 1);
                
                // 复制基本属性
                BeanUtils.copyProperties(entity, vo);
                
                // 格式化数据更新时间
                if (entity.getVDate() != null) {
                    vo.setDataUpdateTime(entity.getVDate());
                }
                
                // 设置统计数据（这里使用降雨量作为示例，实际应该根据业务需求计算）
                vo.setMonthlyMaxValue(entity.getVMax());
                vo.setMonthlyMinValue(entity.getVMin());
                vo.setMonthlyAvgValue(entity.getVAvg());
                vo.setMonthlyRecordValue(entity.getVNum());

                voList.add(vo);
            }
            
            voPage.setRecords(voList);
            return voPage;

        } catch (Exception e) {
            log.error("获取月度数据统计列表异常", e);
            return new Page<>();
        }
    }

    @Override
    public MonthlyChartVO getMonthlyStatsChart(MonthlyStatsQueryDTO monthlyStatsQueryDTO) {
        try {
            log.info("获取月度统计趋势图数据，企业ID: {}, 开始时间: {}, 结束时间: {}", 
                    monthlyStatsQueryDTO.getCompanyId(), monthlyStatsQueryDTO.getStartTime(), monthlyStatsQueryDTO.getEndTime());

            MonthlyChartVO chartVO = new MonthlyChartVO();
            
            // 1. 解析时间参数
            LocalDateTime startDateTime = parseDateTime(monthlyStatsQueryDTO.getStartTime());
            LocalDateTime endDateTime = parseDateTime(monthlyStatsQueryDTO.getEndTime());

            // 2. 构建查询条件
            LambdaQueryWrapper<SiteMonthlyStatistics> queryWrapper = new LambdaQueryWrapper<>();

            // 企业ID条件
            if (!StringUtils.isEmpty(monthlyStatsQueryDTO.getCompanyId())) {
                ComCompany company=comCompanyService.getById(monthlyStatsQueryDTO.getCompanyId());
                if (company!=null&&company.getExtraSiteId()!=null) {
                    queryWrapper.eq(SiteMonthlyStatistics::getSiteId,company.getExtraSiteId());
                }
            }
            

            // 时间范围条件
            queryWrapper.between(SiteMonthlyStatistics::getVDate, startDateTime, endDateTime);
            
            // 按监测时间排序
            queryWrapper.orderByAsc(SiteMonthlyStatistics::getVDate);

            // 3. 查询数据
            List<SiteMonthlyStatistics> dataList = siteMonthlyStatisticsService.list(queryWrapper);
            
//            if (dataList.isEmpty()) {
//                chartVO.setTimeList(new ArrayList<>());
//                chartVO.setChartData(new HashMap<>());
//                return chartVO;
//            }

            // 4. 构建图表数据
            List<String> timeList = new ArrayList<>();
            List<String> maxValues = new ArrayList<>();
            List<String> minValues = new ArrayList<>();
            List<String> avgValues = new ArrayList<>();

            LocalDate index=startDateTime.toLocalDate();
            Map<LocalDate,List<SiteMonthlyStatistics>> localDateListMap=dataList.stream().collect(Collectors.groupingBy(SiteMonthlyStatistics::getVDate));
            while (index.compareTo(endDateTime.toLocalDate()) <=0) {
                timeList.add(index.format(DateTimeFormatter.ofPattern("yyyy-MM-dd")));
                List<SiteMonthlyStatistics> siteMonthlyStatistics=localDateListMap.get(index);
                if (CollectionUtils.isEmpty(siteMonthlyStatistics)) {
                    maxValues.add(String.format("%.2f",new BigDecimal(0)));
                    minValues.add(String.format("%.2f",new BigDecimal(0)));
                    avgValues.add(String.format("%.2f",new BigDecimal(0)));
                }else {
                    maxValues.add(String.format("%.2f",siteMonthlyStatistics.get(0).getVMax()));
                    minValues.add(String.format("%.2f",siteMonthlyStatistics.get(0).getVMin()));
                    avgValues.add(String.format("%.2f",siteMonthlyStatistics.get(0).getVAvg()));
                }

                index= index.plusDays(1);
            }
//            // 按月份分组统计
//            Map<String, List<RainfallOutletMonitoring>> monthlyGroups = dataList.stream()
//                .collect(Collectors.groupingBy(data ->
//                    data.getMonitoringTime().format(DateTimeFormatter.ofPattern("yyyy-MM"))));
//
//            for (Map.Entry<String, List<RainfallOutletMonitoring>> entry : monthlyGroups.entrySet()) {
//                String month = entry.getKey();
//                List<RainfallOutletMonitoring> monthData = entry.getValue();
//
//                timeList.add(month);
//
//                // 计算月度统计值
//                BigDecimal maxValue = monthData.stream()
//                    .map(RainfallOutletMonitoring::getRainfall)
//                    .filter(Objects::nonNull)
//                    .max(BigDecimal::compareTo)
//                    .orElse(BigDecimal.ZERO);
//
//                BigDecimal minValue = monthData.stream()
//                    .map(RainfallOutletMonitoring::getRainfall)
//                    .filter(Objects::nonNull)
//                    .min(BigDecimal::compareTo)
//                    .orElse(BigDecimal.ZERO);
//
//                BigDecimal avgValue = monthData.stream()
//                    .map(RainfallOutletMonitoring::getRainfall)
//                    .filter(Objects::nonNull)
//                    .reduce(BigDecimal.ZERO, BigDecimal::add)
//                    .divide(BigDecimal.valueOf(monthData.size()), 2, java.math.RoundingMode.HALF_UP);
//
//                maxValues.add(maxValue.toString());
//                minValues.add(minValue.toString());
//                avgValues.add(avgValue.toString());
//            }
            
            // 5. 设置图表数据
            chartVO.setTimeList(timeList);
            Map<String, List<String>> chartData = new HashMap<>();
            chartData.put("max", maxValues);
            chartData.put("min", minValues);
            chartData.put("avg", avgValues);
            chartVO.setChartData(chartData);
            chartVO.setDataType("RAINFALL");
            chartVO.setPeriod("月度");
            
            // 设置基本信息
            if (!dataList.isEmpty()) {
                SiteMonthlyStatistics firstData = dataList.get(0);

            }
            
            return chartVO;

        } catch (Exception e) {
            log.error("获取月度统计趋势图数据异常", e);
            return new MonthlyChartVO();
        }
    }

    @Override
    public MonthlyChartVO getConductivityTrendChart(MonthlyStatsQueryDTO monthlyStatsQueryDTO) {
        try {
            log.info("获取电导率趋势图数据，企业ID: {}, 开始时间: {}, 结束时间: {}", 
                    monthlyStatsQueryDTO.getCompanyId(), monthlyStatsQueryDTO.getStartTime(), monthlyStatsQueryDTO.getEndTime());

            MonthlyChartVO chartVO = new MonthlyChartVO();
            
            // 1. 解析时间参数
            LocalDateTime startDateTime = parseDateTime(monthlyStatsQueryDTO.getStartTime()).toLocalDate().atTime(0,0,0);
            LocalDateTime endDateTime = parseDateTime(monthlyStatsQueryDTO.getStartTime()).toLocalDate().atTime(23,59,59);

            // 2. 构建查询条件
            LambdaQueryWrapper<RainfallOutletWeatherData> queryWrapper = new LambdaQueryWrapper<>();
            
            // 企业ID条件
            if (!StringUtils.isEmpty(monthlyStatsQueryDTO.getCompanyId())) {
                ComCompany company=comCompanyService.getById(monthlyStatsQueryDTO.getCompanyId());
                if (company!=null&&company.getExtraSiteId()!=null) {
                    queryWrapper.eq(RainfallOutletWeatherData::getSiteId,company.getExtraSiteId());
                }
            }
            
            // 时间范围条件
            queryWrapper.between(RainfallOutletWeatherData::getDataTime, startDateTime, endDateTime);
            
            // 按监测时间排序
            queryWrapper.orderByAsc(RainfallOutletWeatherData::getDataTime);

            // 3. 查询数据
            List<RainfallOutletWeatherData> dataList = rainfallOutletWeatherDataService.list(queryWrapper);

            // 4. 构建图表数据
            List<String> timeList = new ArrayList<>();
            List<String> conductivityValues = new ArrayList<>();
            List<String> rainfallValues = new ArrayList<>();
            
            // 按分钟分组数据
            Map<String, List<RainfallOutletWeatherData>> minuteGroups = dataList.stream()
                .collect(Collectors.groupingBy(data -> 
                    data.getDataTime().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm"))));
            
            // 生成一天1440分钟的时间序列（00:00 到 23:59）
            LocalDateTime currentTime = startDateTime;
            while (!currentTime.isAfter(endDateTime)) {
                String timeKey = currentTime.format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm"));
                timeList.add(currentTime.format(DateTimeFormatter.ofPattern("HH:mm")));
                
                List<RainfallOutletWeatherData> minuteData = minuteGroups.get(timeKey);
                if (minuteData != null && !minuteData.isEmpty()) {
                    // 获取该分钟的电导率（取第一个值，因为每分钟通常只有一个数据点）
                    RainfallOutletWeatherData data = minuteData.get(0);
                    BigDecimal conductivity = data.getFactorValue();
                    BigDecimal rainfall = data.getRainAmount();
                    
                    conductivityValues.add(conductivity != null ? conductivity.toString() : "0.00");
                    rainfallValues.add(rainfall != null ? rainfall.toString() : "0.00");
                } else {
                    // 当前分钟没有数据，尝试查找右侧（后续时间点）的数据
                    RainfallOutletWeatherData rightData = findRightData(currentTime, minuteGroups, endDateTime);
                    if (rightData != null) {
                        BigDecimal conductivity = rightData.getFactorValue();
                        BigDecimal rainfall = rightData.getRainAmount();
                        
                        conductivityValues.add(conductivity != null ? conductivity.toString() : "0.00");
                        rainfallValues.add(rainfall != null ? rainfall.toString() : "0.00");
                    } else {
                        // 右侧也没有数据，使用默认值0
                        conductivityValues.add("0.00");
                        rainfallValues.add("0.00");
                    }
                }
                
                currentTime = currentTime.plusMinutes(1);
            }
            
            // 5. 设置图表数据
            chartVO.setTimeList(timeList);
            Map<String, List<String>> chartData = new HashMap<>();
            chartData.put("conductivityValues", conductivityValues);
            chartData.put("rainfallValues", rainfallValues);
            chartVO.setChartData(chartData);
            chartVO.setDataType("CONDUCTIVITY");
            chartVO.setPeriod("日度");
            
            // 设置基本信息
            if (!dataList.isEmpty()) {
                RainfallOutletWeatherData firstData = dataList.get(0);
                // 可以设置企业名称等信息，如果需要的话
                // chartVO.setCompanyName(firstData.getCompanyName());
            }
            
            return chartVO;

        } catch (Exception e) {
            log.error("获取电导率趋势图数据异常", e);
            return new MonthlyChartVO();
        }
    }

    /**
     * 查找右侧（后续时间点）的数据
     * @param currentTime 当前时间
     * @param minuteGroups 按分钟分组的数据
     * @param endDateTime 结束时间
     * @return 找到的数据，如果没有找到返回null
     */
    private RainfallOutletWeatherData findRightData(LocalDateTime currentTime, 
                                                   Map<String, List<RainfallOutletWeatherData>> minuteGroups, 
                                                   LocalDateTime endDateTime) {
        LocalDateTime searchTime = currentTime.plusMinutes(1);
        
        // 在后续时间点中查找数据，最多查找30分钟内的数据
        int maxSearchMinutes = 30;
        int searchCount = 0;
        
        while (!searchTime.isAfter(endDateTime) && searchCount < maxSearchMinutes) {
            String timeKey = searchTime.format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm"));
            List<RainfallOutletWeatherData> minuteData = minuteGroups.get(timeKey);
            
            if (minuteData != null && !minuteData.isEmpty()) {
                // 找到数据，返回第一个数据点
                return minuteData.get(0);
            }
            
            searchTime = searchTime.plusMinutes(1);
            searchCount++;
        }
        
        // 没有找到数据
        return null;
    }

    @Override
    public Page<SuspectedDischargeVO> getSuspectedDischargeList(SuspectedDischargeQueryDTO suspectedDischargeQueryDTO) {
        try {
            log.info("获取偷漏排列表，企业ID: {}, 开始时间: {}, 结束时间: {}", 
                    suspectedDischargeQueryDTO.getCompanyId(), suspectedDischargeQueryDTO.getStartTime(), suspectedDischargeQueryDTO.getEndTime());

            // 1. 解析时间参数
            LocalDateTime startDateTime = parseDateTime(suspectedDischargeQueryDTO.getStartTime());
            LocalDateTime endDateTime = parseDateTime(suspectedDischargeQueryDTO.getEndTime());

            // 2. 构建查询条件
            LambdaQueryWrapper<RainfallOutletSuspectedDischarge> queryWrapper = new LambdaQueryWrapper<>();
            
            // 站点ID条件
            if (!StringUtils.isEmpty(suspectedDischargeQueryDTO.getCompanyId())) {
                ComCompany company=comCompanyService.getById(suspectedDischargeQueryDTO.getCompanyId());
                if (company!=null&&company.getExtraSiteId()!=null) {
                    queryWrapper.eq(RainfallOutletSuspectedDischarge::getSiteId,company.getExtraSiteId());
                }
            }
            


            
            // 时间范围条件（基于疑似偷排开始时间）
            queryWrapper.between(RainfallOutletSuspectedDischarge::getSuspectedStartTime, startDateTime, endDateTime);
            
            // 按疑似偷排开始时间倒序排列
            queryWrapper.orderByDesc(RainfallOutletSuspectedDischarge::getSuspectedStartTime);

            // 3. 分页查询
            Page<RainfallOutletSuspectedDischarge> page = new Page<>(suspectedDischargeQueryDTO.getPageNum(), suspectedDischargeQueryDTO.getPageSize());
            Page<RainfallOutletSuspectedDischarge> resultPage = rainfallOutletSuspectedDischargeService.page(page, queryWrapper);

            // 4. 转换为VO
            Page<SuspectedDischargeVO> voPage = new Page<>();
            BeanUtils.copyProperties(resultPage, voPage, "records");
            
            List<SuspectedDischargeVO> voList = new ArrayList<>();
            for (int i = 0; i < resultPage.getRecords().size(); i++) {
                RainfallOutletSuspectedDischarge entity = resultPage.getRecords().get(i);
                SuspectedDischargeVO vo = new SuspectedDischargeVO();
                
                // 设置序号（从当前页开始计算）
                vo.setSerialNumber((suspectedDischargeQueryDTO.getPageNum() - 1) * suspectedDischargeQueryDTO.getPageSize() + i + 1);
                
                // 复制基本属性
                BeanUtils.copyProperties(entity, vo);
                
                // 设置疑似偷排漏排时间段
                if (entity.getSuspectedStartTime() != null && entity.getSuspectedEndTime() != null) {
                    String startTimeStr = entity.getSuspectedStartTime().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));
                    String endTimeStr = entity.getSuspectedEndTime().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));
                    vo.setSuspectedTimePeriod(startTimeStr + " ~ " + endTimeStr);
                }
                
                // 设置统计值
                vo.setMaxValue(entity.getFactorMax());
                vo.setMinValue(entity.getFactorMin());
                vo.setAvgValue(entity.getFactorAvg());
                
                voList.add(vo);
            }
            voPage.setRecords(voList);
            return voPage;

        } catch (Exception e) {
            log.error("获取偷漏排列表异常", e);
            return new Page<>();
        }
    }

    @Override
    public List<CompanyRainTreeVO> getCompanyRainTree() {
        List<ComCompany> companies=comCompanyService.list(new LambdaQueryWrapper<ComCompany>()
                .ne(ComCompany::getIsSewagePlant, "1")
                .isNotNull(ComCompany::getExtraSiteId));
        List<RainfallOutletSite> rainfallOutletSites=rainfallOutletSiteService.list();
        List<RainfallOutletMonitoring> rainfallOutletMonitorings=rainfallOutletMonitoringService.list();
        Map<Integer,RainfallOutletSite> rainfallOutletSiteMap=rainfallOutletSites.stream().collect(Collectors.toMap(RainfallOutletSite::getSiteId,i->i));
        List<CompanyRainTreeVO> voList=companies.stream().map(i->{
            CompanyRainTreeVO vo=new CompanyRainTreeVO();
            BeanUtils.copyProperties(i,vo);
            long warnCount=iWarningService.count(new LambdaQueryWrapper<Warning>()
                    .eq(Warning::getCompanyId,i.getId())
                    .between(Warning::getWarningTime,LocalDate.now().atTime(0,0,0),LocalDateTime.now()));
            if (warnCount>0) {
                vo.setStatus("2");
            }else {
                vo.setStatus("1");
            }
            RainfallOutletSite rainfallOutletSite=rainfallOutletSiteMap.get(i.getExtraSiteId());
            if (rainfallOutletSite!=null){
                vo.setBaseValue(rainfallOutletSite.getBaselineValue()+"");
            }
            RainfallOutletMonitoring rainMonitoring=rainfallOutletMonitorings.stream().filter(rainfallOutletMonitoring -> "雨排口阀门".equals(rainfallOutletMonitoring.getDeviceName())&&i.getId().equals(rainfallOutletMonitoring.getCompanyId()))
                    .findFirst().orElse(null);
            RainfallOutletMonitoring emergencyMonitoring=rainfallOutletMonitorings.stream().filter(rainfallOutletMonitoring -> "应急池阀门".equals(rainfallOutletMonitoring.getDeviceName())&&i.getId().equals(rainfallOutletMonitoring.getCompanyId()))
                    .findFirst().orElse(null);
            if (rainMonitoring!=null){
                vo.setRainOutLetOpenStatus(rainMonitoring.getRainOutletValveStatus());
            }else {
                vo.setRainOutLetOpenStatus("0");
            }
            if (emergencyMonitoring!=null){
                vo.setEmergencyOpenStatus(emergencyMonitoring.getEmergencyPoolValveStatus());
            }else {
                vo.setEmergencyOpenStatus("0");
            }
            vo.setRainOutLetOnlineStatus("1");
            return vo;
        }).collect(Collectors.toList());
        return voList;
    }

    @Override
    public List<SewagePlantTreeVO> getSewagePlantTree() {
        try {
            log.info("获取污水厂树数据");

            // 1. 获取所有污水厂手工检测数据
            List<SewagePlantManualDetection> allData = sewagePlantManualDetectionService.list();

            // 2. 按污水厂名称分组
            Map<String, List<SewagePlantManualDetection>> plantGroups = allData.stream()
                .collect(Collectors.groupingBy(SewagePlantManualDetection::getPlantName));

            List<SewagePlantTreeVO> treeList = new ArrayList<>();
            List<SewagePlantWastewaterType> sewagePlantWastewaterTypes=sewagePlantWastewaterTypeService.list();
            Map<String,List<SewagePlantWastewaterType>> sewageMap=sewagePlantWastewaterTypes.stream().collect(Collectors.groupingBy(SewagePlantWastewaterType::getPlantName));

            for (Map.Entry<String, List<SewagePlantManualDetection>> entry : plantGroups.entrySet()) {
                String plantName = entry.getKey();
                List<SewagePlantManualDetection> plantData = entry.getValue();

                // 创建污水厂节点
                SewagePlantTreeVO plantNode = new SewagePlantTreeVO();
                plantNode.setId(plantName);
                plantNode.setName(plantName);
                plantNode.setType("plant");
                plantNode.setParentId(null);
                plantNode.setPlantName(plantName);
                plantNode.setPlantCode(plantData.get(0).getPlantCode());
                plantNode.setLeaf(false);
                plantNode.setDataCount((long) plantData.size());
                
                // 设置最新检测日期
                String latestDate = plantData.stream()
                    .map(data -> data.getDetectionDate())
                    .filter(Objects::nonNull)
                    .max(LocalDate::compareTo)
                    .map(date -> date.format(DateTimeFormatter.ofPattern("yyyy-MM-dd")))
                    .orElse("");
                plantNode.setLatestDetectionDate(latestDate);

                // 按出水口类型分组

                List<SewagePlantTreeVO> outletNodes = new ArrayList<>();
                List<SewagePlantWastewaterType> sewagePlantManualDetections=sewageMap.get(plantName);
                for (SewagePlantWastewaterType sewagePlantManualDetection : sewagePlantManualDetections) {

                    // 创建出水口节点
                    SewagePlantTreeVO outletNode = new SewagePlantTreeVO();
                    outletNode.setId(sewagePlantManualDetection.getWastewaterTypeName());
                    outletNode.setName(sewagePlantManualDetection.getWastewaterTypeName());
                    outletNode.setType("outlet");
                    outletNode.setParentId(plantName);
                    outletNode.setPlantCode(sewagePlantManualDetection.getPlantCode());
                    outletNode.setPlantName(plantName);
                    outletNode.setOutletType(sewagePlantManualDetection.getWastewaterTypeName());
                    outletNode.setLeaf(true);
                    outletNode.setChildren(new ArrayList<>());

                    // 设置最新检测日期


                    outletNodes.add(outletNode);
                }

                plantNode.setChildren(outletNodes);
                treeList.add(plantNode);
            }

            return treeList;

        } catch (Exception e) {
            log.error("获取污水厂树数据异常", e);
            return new ArrayList<>();
        }
    }

    @Override
    public SewagePlantDetailVO getSewagePlantDetail(SewagePlantDetailDTO sewagePlantDetailDTO) {
        try {
            log.info("获取污水厂数据详情，污水厂名称: {}, 出水口类型: {}, 开始时间: {}, 结束时间: {}", 
                    sewagePlantDetailDTO.getPlantCode(), sewagePlantDetailDTO.getOutletType(),
                    sewagePlantDetailDTO.getStartTime(), sewagePlantDetailDTO.getEndTime());

            SewagePlantDetailVO detailVO = new SewagePlantDetailVO();

            // 1. 解析时间参数
            LocalDateTime startDateTime = parseDateTime(sewagePlantDetailDTO.getStartTime());
            LocalDateTime endDateTime = parseDateTime(sewagePlantDetailDTO.getEndTime());

            // 2. 构建查询条件
            LambdaQueryWrapper<SewagePlantManualDetection> queryWrapper = new LambdaQueryWrapper<>();
            
            // 污水厂名称条件
            if (!StringUtils.isEmpty(sewagePlantDetailDTO.getPlantCode())) {
                queryWrapper.eq(SewagePlantManualDetection::getPlantCode, sewagePlantDetailDTO.getPlantCode());
            }
            
            // 出水口类型条件
            if (!StringUtils.isEmpty(sewagePlantDetailDTO.getOutletType())) {
                queryWrapper.eq(SewagePlantManualDetection::getOutletType, sewagePlantDetailDTO.getOutletType());
            }
            queryWrapper.orderByDesc(SewagePlantManualDetection::getDetectionDate);

            // 时间范围条件
            queryWrapper.and(w -> w
                    .isNotNull(SewagePlantManualDetection::getChromium6)
                    .or()
                    .isNotNull(SewagePlantManualDetection::getNickelTotal)
                    .or()
                    .isNotNull(SewagePlantManualDetection::getChromiumTotal)
            );
            List<SewagePlantManualDetection> allList = sewagePlantManualDetectionService.list(queryWrapper);
            queryWrapper.between(SewagePlantManualDetection::getDetectionDate,
                    startDateTime.toLocalDate(), endDateTime.toLocalDate());
            // 按检测日期倒序排列

            // 3. 查询数据
            List<SewagePlantManualDetection> dataList = sewagePlantManualDetectionService.list(queryWrapper);
            
//            if (dataList.isEmpty()) {
//                log.warn("未找到污水厂数据，污水厂编码: {}, 出水口类型: {}",
//                        sewagePlantDetailDTO.getPlantCode(), sewagePlantDetailDTO.getOutletType());
//                return detailVO;
//            }

            // 4. 设置基本信息
            SewagePlantManualDetection firstData = allList.get(0);
            detailVO.setPlantName(firstData.getPlantName());
            detailVO.setPlantCode(firstData.getPlantCode());
            detailVO.setOutletType(firstData.getOutletType());
            detailVO.setStatus("正常");
            detailVO.setLastUpdateTime(firstData.getDetectionDate().format(DateTimeFormatter.ofPattern("yyyy-MM-dd")));

            // 5. 构建运行数据列表
            List<SewagePlantRunningDataVO> runningDataList = buildSewagePlantRunningDataList(allList);
            detailVO.setRunningDataList(runningDataList);

            // 6. 构建时间序列图表数据
            Map<String, List<String>> chartData = buildSewagePlantChartData(dataList, startDateTime, endDateTime);
            detailVO.setChartData(chartData);

            return detailVO;

        } catch (Exception e) {
            log.error("获取污水厂数据详情异常", e);
            return new SewagePlantDetailVO();
        }
    }

    /**
     * 构建污水厂运行数据列表
     */
    private List<SewagePlantRunningDataVO> buildSewagePlantRunningDataList(List<SewagePlantManualDetection> dataList) {
        List<SewagePlantRunningDataVO> runningDataList = new ArrayList<>();

        LocalDate lastDay=null;
        for (SewagePlantManualDetection data : dataList) {
            SewagePlantRunningDataVO vo = new SewagePlantRunningDataVO();
            if (lastDay!=null&&lastDay.compareTo(data.getDetectionDate())>0) {
                continue;
            }else {
                // 设置检测日期
                if (data.getDetectionDate() != null) {
                    lastDay = data.getDetectionDate();
                    vo.setDetectionDate(data.getDetectionDate().format(DateTimeFormatter.ofPattern("yyyy-MM-dd")));
                }
            }
            
            // 设置基本属性
            vo.setOutletType(data.getOutletType());
            vo.setChromium6(data.getChromium6());
            vo.setNickelTotal(data.getNickelTotal());
            vo.setChromiumTotal(data.getChromiumTotal());
            vo.setInputBy(data.getInputBy());
            vo.setFactorName(getSewagePlantFactorName(data));
            vo.setSort(data.getSort());
            // 设置录入日期
            if (data.getInputDate() != null) {
                vo.setInputDate(data.getInputDate().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")));
            }
            
            // 设置状态（根据检测值判断）
            vo.setStatus(determineSewagePlantStatus(data));
            
            runningDataList.add(vo);
        }
        runningDataList=runningDataList.stream().sorted(Comparator.comparing(SewagePlantRunningDataVO::getSort)).collect(Collectors.toList());
        return runningDataList;
    }

    /**
     * 构建污水厂图表数据
     */
    private Map<String, List<String>> buildSewagePlantChartData(List<SewagePlantManualDetection> dataList, 
            LocalDateTime startDateTime, LocalDateTime endDateTime) {
        Map<String, List<String>> chartData = new HashMap<>();
        
        // 生成时间序列（按天）
        List<String> timeList = generateSewagePlantTimeSequence(startDateTime, endDateTime);
        chartData.put("date", timeList);
        
        // 按出水口类型分组数据
        Map<String, List<SewagePlantManualDetection>> outletGroupedData = dataList.stream()
            .collect(Collectors.groupingBy(SewagePlantManualDetection::getOutletType));
        
        // 为每个出水口类型生成检测因子数据
        for (Map.Entry<String, List<SewagePlantManualDetection>> entry : outletGroupedData.entrySet()) {
            String outletType = entry.getKey();
            List<SewagePlantManualDetection> outletData = entry.getValue();
            
            // 六价铬数据
            List<String> chromium6Data = timeList.stream()
                .map(time -> {
                    SewagePlantManualDetection closestData = findClosestSewagePlantDataForTime(outletData, time);
                    return closestData != null && closestData.getChromium6() != null ? 
                        closestData.getChromium6().toString() : "0";
                })
                .collect(Collectors.toList());
            chartData.put(outletType + "(六价铬)", chromium6Data);
            
            // 总镍数据
            List<String> nickelData = timeList.stream()
                .map(time -> {
                    SewagePlantManualDetection closestData = findClosestSewagePlantDataForTime(outletData, time);
                    return closestData != null && closestData.getNickelTotal() != null ? 
                        closestData.getNickelTotal().toString() : "0";
                })
                .collect(Collectors.toList());
            chartData.put(outletType + "(总镍)", nickelData);
            
            // 总铬数据
            List<String> chromiumData = timeList.stream()
                .map(time -> {
                    SewagePlantManualDetection closestData = findClosestSewagePlantDataForTime(outletData, time);
                    return closestData != null && closestData.getChromiumTotal() != null ? 
                        closestData.getChromiumTotal().toString() : "0";
                })
                .collect(Collectors.toList());
            chartData.put(outletType + "(总铬)", chromiumData);
        }
        
        return chartData;
    }

    /**
     * 生成污水厂时间序列（按天）
     */
    private List<String> generateSewagePlantTimeSequence(LocalDateTime startDateTime, LocalDateTime endDateTime) {
        List<String> timeList = new ArrayList<>();
        LocalDate currentDate = startDateTime.toLocalDate();
        LocalDate endDate = endDateTime.toLocalDate();
        
        while (!currentDate.isAfter(endDate)) {
            timeList.add(currentDate.toString());
            currentDate = currentDate.plusDays(1);
        }
        
        return timeList;
    }

    /**
     * 查找最接近指定时间的污水厂数据
     */
    private SewagePlantManualDetection findClosestSewagePlantDataForTime(List<SewagePlantManualDetection> dataList, String timeStr) {
        if (dataList.isEmpty()) {
            return null;
        }

        LocalDate targetDate = LocalDate.parse(timeStr);
        
       return dataList.stream().filter(i->targetDate.compareTo(i.getDetectionDate())==0).findFirst().orElse(new SewagePlantManualDetection());
        
    }

    /**
     * 判断污水厂检测状态
     */
    private String determineSewagePlantStatus(SewagePlantManualDetection data) {
        // 这里可以根据具体的业务规则判断状态
        // 例如：如果检测值超过某个阈值，则状态为"异常"
        if (data.getChromium6() != null && data.getChromium6().compareTo(new BigDecimal("0.1")) > 0) {
            return "异常";
        }
        if (data.getNickelTotal() != null && data.getNickelTotal().compareTo(new BigDecimal("0.1")) > 0) {
            return "异常";
        }
        if (data.getChromiumTotal() != null && data.getChromiumTotal().compareTo(new BigDecimal("0.1")) > 0) {
            return "异常";
        }
        return "正常";
    }

    @Override
    public Page<SewagePlantListVO> getSewagePlantList(SewagePlantListDTO sewagePlantListDTO) {
        try {
            log.info("获取污水厂排水口运行列表，污水厂编码: {}, 出水口类型: {}, 开始时间: {}, 结束时间: {}", 
                    sewagePlantListDTO.getPlantCode(), sewagePlantListDTO.getOutletType(), 
                    sewagePlantListDTO.getStartTime(), sewagePlantListDTO.getEndTime());

            // 1. 解析时间参数
            LocalDateTime startDateTime = parseDateTime(sewagePlantListDTO.getStartTime());
            LocalDateTime endDateTime = parseDateTime(sewagePlantListDTO.getEndTime());

            // 2. 构建查询条件
            LambdaQueryWrapper<SewagePlantManualDetection> queryWrapper = new LambdaQueryWrapper<>();
            
            // 污水厂编码条件
            if (!StringUtils.isEmpty(sewagePlantListDTO.getPlantCode())) {
                queryWrapper.eq(SewagePlantManualDetection::getPlantCode, sewagePlantListDTO.getPlantCode());
            }
            
            // 出水口类型条件
            if (!StringUtils.isEmpty(sewagePlantListDTO.getOutletType())) {
                queryWrapper.eq(SewagePlantManualDetection::getOutletType, sewagePlantListDTO.getOutletType());
            }
            
            // 时间范围条件
            queryWrapper.between(SewagePlantManualDetection::getDetectionDate, 
                    startDateTime.toLocalDate(), endDateTime.toLocalDate());
            queryWrapper.and(w -> w
                    .isNotNull(SewagePlantManualDetection::getChromium6)
                    .or()
                    .isNotNull(SewagePlantManualDetection::getNickelTotal)
                    .or()
                    .isNotNull(SewagePlantManualDetection::getChromiumTotal)
            );
            // 按创建时间倒序排列
            queryWrapper.orderByDesc(SewagePlantManualDetection::getDetectionDate);

            // 3. 分页查询
            Page<SewagePlantManualDetection> page = new Page<>(sewagePlantListDTO.getPageNum(), sewagePlantListDTO.getPageSize());
            Page<SewagePlantManualDetection> resultPage = sewagePlantManualDetectionService.page(page, queryWrapper);

            // 4. 转换为VO
            Page<SewagePlantListVO> voPage = new Page<>();
            BeanUtils.copyProperties(resultPage, voPage, "records");
            
            List<SewagePlantListVO> voList = new ArrayList<>();
            for (SewagePlantManualDetection entity : resultPage.getRecords()) {
                SewagePlantListVO vo = new SewagePlantListVO();
                BeanUtils.copyProperties(entity, vo);
                
                // 设置状态
                vo.setStatus(determineSewagePlantStatus(entity));
                
                // 设置检测因子名称
                vo.setFactorName(getSewagePlantFactorName(entity));
                
                // 格式化日期
                if (entity.getDetectionDate() != null) {
                    vo.setDetectionDate(entity.getDetectionDate().format(DateTimeFormatter.ofPattern("yyyy-MM-dd")));
                }
                if (entity.getInputDate() != null) {
                    vo.setInputDate(entity.getInputDate().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")));
                }
                if (entity.getCreateTime() != null) {
                    vo.setCreateTime(entity.getCreateTime().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")));
                }
                
                voList.add(vo);
            }
            
            voPage.setRecords(voList);
            return voPage;

        } catch (Exception e) {
            log.error("获取污水厂排水口运行列表异常", e);
            return new Page<>();
        }
    }

    @Override
    public EnterpriseMapDataVO getEnterpriseMapDataWithChart(String companyId) {
        EnterpriseMapDataVO mapData = new EnterpriseMapDataVO();

        // 园区企业列表
        LambdaQueryWrapper<ComCompany> comCompanyLambdaQueryWrapper=new LambdaQueryWrapper<ComCompany>();
        if (!StringUtils.isEmpty(companyId)) {
            comCompanyLambdaQueryWrapper.eq(ComCompany::getId,companyId);
        }
        List<ComCompany> companies = comCompanyService.list(comCompanyLambdaQueryWrapper);
        List<ComWorkshop> comWorkshops=comWorkshopService.list();
        List<ComProduction> comProductions=comProductionService.list();
        Map<String,List<ComProduction>> comProductionMap=comProductions.stream().collect(Collectors.groupingBy(ComProduction::getCompanyId));
        List<EnterpriseMapVO> enterpriseList = companies.stream()
                .map(company -> {
                    EnterpriseMapVO vo = new EnterpriseMapVO();
                    vo.setCompanyId(company.getId());
                    vo.setCompanyName(company.getCompanyName());
                    vo.setLongitude(company.getLongitude());
                    vo.setIndustryType(IndustryTypeEnum.getDesc(company.getIndustryType()));
                    vo.setEnvironmentalOfficer(company.getEnvironmentalOfficer());
                    vo.setEnvironmentalOfficerPhone(company.getEnvironmentalOfficerPhone());
                    vo.setCompanyAbbreviation(company.getCompanyAbbreviation());
                    vo.setLatitude(company.getLatitude());
                    vo.setCodeStatus(new Random().nextBoolean() ? "绿码" : "黄码");
                    vo.setWorkshopCount((int)comWorkshops.stream().filter(i->company.getId().equals(i.getCompanyId())).count());
                    List<ComProduction> comProductionsList=comProductionMap.get(company.getId());
                    if (CollectionUtils.isEmpty(comProductionsList)) {
                        vo.setProductionLineCount(0);
                    }else {
                        vo.setProductionLineCount(comProductionsList.stream().filter(i->i.getEnterpriseProductionLineCou()!=null)
                                .map(ComProduction::getApprovedLineCount).reduce((a,b)->a+b).orElse(0));
                    }
                    vo.setRainOutLetOpenStatus(new Random().nextInt(1)+"");
                    vo.setPollutionDischargeInfo(getPollutionTypeByCode(company.getPollutionDischargeInfo()));
                    vo.setIsSewagePlant(company.getIsSewagePlant());
                    if ("1".equals(company.getIsSewagePlant())){
                        vo.setPreDischargeWastewaterChartVO(frontEnterpriseService.getPreDischargeWastewaterChart(null));
                    }else {
                        vo.setEnterpriseWastewaterChartVO(frontEnterpriseService.getRainfallOutletChartForHomePage());
                    }
                    return vo;
                })
                .collect(Collectors.toList());
        mapData.setEnterpriseList(enterpriseList);

        // 园区统计信息
//        Map<String, Object> parkStatistics = new HashMap<>();
//        parkStatistics.put("totalEnterprises", companies.size());
//        parkStatistics.put("greenCodeEnterprises", (int) (companies.size() * 0.9));
//        parkStatistics.put("yellowCodeEnterprises", (int) (companies.size() * 0.08));
//        parkStatistics.put("redCodeEnterprises", (int) (companies.size() * 0.02));
//
//        // 车间和产线统计
//        long totalWorkshops = comWorkshopService.count();
//        long totalProductionLines = comProductionService.count();
//        parkStatistics.put("totalWorkshops", totalWorkshops);
//        parkStatistics.put("totalProductionLines", totalProductionLines);
//        mapData.setParkStatistics(parkStatistics);
        List<EnterpriseDetailVO> enterpriseDetailVOS=Arrays.asList(new EnterpriseDetailVO("应急阀状态","1")
                ,new EnterpriseDetailVO("雨排口闸阀状态","1"),new EnterpriseDetailVO("雨水池液位计",new Random().nextInt(100)+"")
                ,new EnterpriseDetailVO("应急池液位计",new Random().nextInt(100)+"")
                ,new EnterpriseDetailVO("综合废气PH",new  Random().nextInt(100)+"")
        );

        mapData.setParkStatistics(enterpriseDetailVOS);
        return mapData;
    }

    @Override
    public ParkSumaryVO parkSummary() {
        ParkSumaryVO parkSumaryVO = new ParkSumaryVO();
        parkSumaryVO.setCompanyCount((int)comCompanyService.count());
        parkSumaryVO.setWorkShopCount((int)comWorkshopService.count());
        parkSumaryVO.setLineAllCount((int)comProductionService.list().stream().filter(i->i.getApprovedLineCount()!=null).map(ComProduction::getApprovedLineCount).reduce(0, Integer::sum));
        parkSumaryVO.setLineHaveCount((int)comProductionService.list().stream().filter(i->i.getEnterpriseProductionLineCou()!=null).map(ComProduction::getEnterpriseProductionLineCou).reduce(0, Integer::sum));
        return parkSumaryVO;
    }

    @Override
    public EnterpriseOutletSummaryVO enterpriseOutletSummaryVO(RainFallOutletHisDataDTO rainFallOutletHisDataDTO) {
        EnterpriseOutletSummaryVO enterpriseOutletSummaryVO = new EnterpriseOutletSummaryVO();
        
        // 获取园区排口监控数据
        List<ParkOutletMonitoring> parkOutletMonitorings = parkOutletMonitoringService.list(
                new LambdaQueryWrapper<ParkOutletMonitoring>()
                        .eq(ParkOutletMonitoring::getOutletAbbreviation, "排口" + rainFallOutletHisDataDTO.getId())
                        .ne(ParkOutletMonitoring::getDeviceName, "手自一体阀")
                        .eq(ParkOutletMonitoring::getDelFlag, "0")
        );
        parkOutletMonitorings.forEach(i->{
            if ("开/关".equals(i.getUnit())){
                i.setUnit("");
            }
        });
        // 获取园区排口历史数据（最近的数据）
        List<ParkOutletMonitoringLog> recentLogs = parkOutletMonitoringLogService.list(
                new LambdaQueryWrapper<ParkOutletMonitoringLog>()
                        .in(ParkOutletMonitoringLog::getMonitoringId,
                            parkOutletMonitorings.stream().map(ParkOutletMonitoring::getOutletId).collect(Collectors.toList()))
                        .orderByDesc(ParkOutletMonitoringLog::getLogTime)
                        .last("limit 10")
        );
        
        // 按监测ID分组历史数据
        Map<String, List<ParkOutletMonitoringLog>> logGroups = recentLogs.stream()
                .collect(Collectors.groupingBy(ParkOutletMonitoringLog::getMonitoringId));
        
        // 构建企业排口数据列表
        List<EnterpriseOutletVO> enterpriseOutletVOS = new ArrayList<>();

        for (ParkOutletMonitoring monitoring : parkOutletMonitorings) {
            EnterpriseOutletVO enterpriseOutletVO = new EnterpriseOutletVO();
            enterpriseOutletVO.setId(monitoring.getOutletId());
            enterpriseOutletVO.setCompanyName(monitoring.getOutletName());

            // 设置设备状态
            enterpriseOutletVO.setDeviceStatus("1".equals(monitoring.getStatus()) ? "正常" : "离线");

            // 获取该监测点的最新日志数据
            List<ParkOutletMonitoringLog> monitoringLogs = logGroups.getOrDefault(monitoring.getOutletId(), new ArrayList<>());

            if (!monitoringLogs.isEmpty()) {
                // 获取最新的日志记录
                ParkOutletMonitoringLog latestLog = monitoringLogs.get(0);

                // 根据监测因子设置对应的数值
                String factorCode = monitoring.getMonitoringFactorCode();
                if ("PH".equals(factorCode)) {
                    enterpriseOutletVO.setPh(latestLog.getMonitoringValue() != null ?
                            latestLog.getMonitoringValue().toString() : "0.00");
                } else if ("ORP".equals(factorCode)) {
                    enterpriseOutletVO.setOrp(latestLog.getMonitoringValue() != null ?
                            latestLog.getMonitoringValue().toString() : "0.00");
                } else if ("DDL".equals(factorCode)) {
                    enterpriseOutletVO.setConductivity(latestLog.getMonitoringValue() != null ?
                            latestLog.getMonitoringValue().toString() : "0.00");
                }

                // 设置分析时间
                if (latestLog.getLogTime() != null) {
                    enterpriseOutletVO.setAnaTime(latestLog.getLogTime().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")));
                }
            }

            // 设置其他默认值（这些可能需要从其他数据源获取）


            enterpriseOutletVOS.add(enterpriseOutletVO);
        }

        // 按监测因子类型分组，确保每个排口有完整的数据
        Map<String, List<EnterpriseOutletVO>> groupedByOutlet = enterpriseOutletVOS.stream()
                .collect(Collectors.groupingBy(EnterpriseOutletVO::getId));

        List<EnterpriseOutletVO> finalEnterpriseOutletVOS = new ArrayList<>();
        for (Map.Entry<String, List<EnterpriseOutletVO>> entry : groupedByOutlet.entrySet()) {
            List<EnterpriseOutletVO> outletList = entry.getValue();
            if (outletList.size() > 1) {
                // 合并同一排口的多个监测因子数据
                EnterpriseOutletVO mergedOutlet = outletList.get(0);
                for (int i = 1; i < outletList.size(); i++) {
                    EnterpriseOutletVO outlet = outletList.get(i);
                    if (outlet.getPh() != null && !"0.00".equals(outlet.getPh())) {
                        mergedOutlet.setPh(outlet.getPh());
                    }
                    if (outlet.getOrp() != null && !"0.00".equals(outlet.getOrp())) {
                        mergedOutlet.setOrp(outlet.getOrp());
                    }
                    if (outlet.getConductivity() != null && !"0.00".equals(outlet.getConductivity())) {
                        mergedOutlet.setConductivity(outlet.getConductivity());
                    }
                }
                finalEnterpriseOutletVOS.add(mergedOutlet);
            } else {
                finalEnterpriseOutletVOS.addAll(outletList);
            }
        }
        
        // 设置分页数据
//        Page<EnterpriseOutletVO> page = new Page<>(1, 1);
//        page.setRecords(finalEnterpriseOutletVOS);
//        page.setTotal(finalEnterpriseOutletVOS.size());
        // 获取园区排口历史数据（最近的数据）
        Page<EnterpriseOutletVO> recentLogsPage = parkOutletMonitoringLogService.enterpriseOutletSummaryVO(
                new Page<>(rainFallOutletHisDataDTO.getPageNum(),rainFallOutletHisDataDTO.getPageSize()),
                rainFallOutletHisDataDTO
        );
        Page<EnterpriseOutletVO> enterpriseOutletVOPage=new Page<>();
        enterpriseOutletVOPage.setRecords(recentLogsPage.getRecords().stream().map(i->{
            EnterpriseOutletVO enterpriseOutletVO=new EnterpriseOutletVO();
            BeanUtils.copyProperties(i,enterpriseOutletVO);
            return enterpriseOutletVO;
        }).collect(Collectors.toUnmodifiableList()));
        enterpriseOutletVOPage.setTotal(recentLogsPage.getTotal());
        enterpriseOutletSummaryVO.setEnterpriseOutletVOPage(enterpriseOutletVOPage);
        enterpriseOutletSummaryVO.setParkOutletMonitorings(parkOutletMonitorings);

        // 设置最后更新时间
        if (!CollectionUtils.isEmpty(parkOutletMonitorings)) {
            // 找到最新的监测时间
            LocalDateTime latestTime = parkOutletMonitorings.stream()
                    .filter(monitoring -> monitoring.getMonitoringTime() != null)
                    .map(ParkOutletMonitoring::getMonitoringTime)
                    .max(LocalDateTime::compareTo)
                    .orElse(LocalDateTime.now());
            enterpriseOutletSummaryVO.setLastTime(latestTime.format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")));
        }
        
        return enterpriseOutletSummaryVO;
    }

    /**
     * 获取污水厂检测因子名称
     */
    private String getSewagePlantFactorName(SewagePlantManualDetection entity) {
        StringBuilder factorNames = new StringBuilder();
        
        if (entity.getChromium6() != null) {
            factorNames.append("六价铬");
        }
        if (entity.getNickelTotal() != null) {
            if (factorNames.length() > 0) {
                factorNames.append("、");
            }
            factorNames.append("总镍");
        }
        if (entity.getChromiumTotal() != null) {
            if (factorNames.length() > 0) {
                factorNames.append("、");
            }
            factorNames.append("总铬");
        }
        
        return factorNames.length() > 0 ? factorNames.toString() : "无检测因子";
    }
    
    /**
     * 检查企业当日废水数据是否正常
     * @param sewageWarningConfigs 企业废水预警配置列表
     * @param todayInflowManagements 当日废水含量数据列表
     * @return 正常企业数
     */
    private Integer checkIsNormal(List<SewageWarningConfig> sewageWarningConfigs, List<InflowManagement> todayInflowManagements) {
        if (sewageWarningConfigs == null || sewageWarningConfigs.isEmpty() || 
            todayInflowManagements == null || todayInflowManagements.isEmpty()) {
            return sewageWarningConfigs.size();
        }
        
        int normalCount = 0;
        
        // 按企业ID分组配置
        Map<String, List<SewageWarningConfig>> configsByCompany = sewageWarningConfigs.stream()
                .collect(Collectors.groupingBy(SewageWarningConfig::getCompanyId));
        
        // 按企业ID分组当日数据
        Map<String, List<InflowManagement>> dataByCompany = todayInflowManagements.stream()
                .collect(Collectors.groupingBy(InflowManagement::getCompanyId));
        
        // 检查每个企业的数据是否正常
        for (Map.Entry<String, List<SewageWarningConfig>> entry : configsByCompany.entrySet()) {
            String companyId = entry.getKey();
            List<SewageWarningConfig> companyConfigs = entry.getValue();
            List<InflowManagement> companyData = dataByCompany.getOrDefault(companyId, new ArrayList<>());
            
            // 判断该企业当日数据是否正常
            if (isCompanyDataNormal(companyConfigs, companyData)) {
                normalCount++;
            }
        }
        
        return normalCount;
    }
    
    /**
     * 判断单个企业当日数据是否正常
     * @param companyConfigs 企业配置列表
     * @param companyData 企业当日数据列表
     * @return true-正常，false-异常
     */
    private boolean isCompanyDataNormal(List<SewageWarningConfig> companyConfigs, List<InflowManagement> companyData) {
        if (companyConfigs == null || companyConfigs.isEmpty() || companyData == null || companyData.isEmpty()) {
            return true; // 没有配置或数据时认为正常
        }
        
        // 按废水类型分组配置
        Map<String, SewageWarningConfig> configMap = companyConfigs.stream()
                .collect(Collectors.toMap(
                    SewageWarningConfig::getWasteWaterType,
                    config -> config,
                    (existing, replacement) -> existing // 如果有重复键，保留第一个
                ));
        
        // 按废水类型分组当日数据
        Map<String, List<InflowManagement>> dataMap = companyData.stream()
                .collect(Collectors.groupingBy(InflowManagement::getWasteWaterType));
        
        // 检查每种废水类型的数据是否正常
        for (Map.Entry<String, SewageWarningConfig> configEntry : configMap.entrySet()) {
            String wasteWaterType = configEntry.getKey();
            SewageWarningConfig config = configEntry.getValue();
            List<InflowManagement> typeData = dataMap.getOrDefault(wasteWaterType, new ArrayList<>());
            
            // 检查该废水类型的数据是否正常
            if (!isWasteWaterTypeDataNormal(config, typeData)) {
                log.info("企业废水数据异常，企业ID: {}, 废水类型: {}, 配置ID: {}", 
                        config.getCompanyId(), wasteWaterType, config.getId());
                return false; // 只要有一种废水类型异常，整个企业就认为异常
            }
        }
        
        return true; // 所有废水类型都正常
    }
    
    /**
     * 判断特定废水类型的数据是否正常
     * @param config 废水预警配置
     * @param typeData 该废水类型的当日数据
     * @return true-正常，false-异常
     */
    private boolean isWasteWaterTypeDataNormal(SewageWarningConfig config, List<InflowManagement> typeData) {
        if (typeData == null || typeData.isEmpty()) {
            return true; // 没有数据时认为正常
        }
        
        // 获取最新的数据（假设按检测日期排序，取最新的）
        InflowManagement latestData = typeData.stream()
                .max(Comparator.comparing(InflowManagement::getDetectionDate))
                .orElse(typeData.get(0));
        
        // 检查六价铬
        if ("1".equals(config.getMonitorHexavalentChromium()) && 
            config.getHexavalentChromiumThreshold() != null && 
            latestData.getHexavalentChromiumValue() != null) {
            
            if (latestData.getHexavalentChromiumValue().compareTo(config.getHexavalentChromiumThreshold()) > 0) {
                log.debug("六价铬超标，企业ID: {}, 检测值: {}, 阈值: {}", 
                        config.getCompanyId(), latestData.getHexavalentChromiumValue(), config.getHexavalentChromiumThreshold());
                return false;
            }
        }
        
        // 检查总铬
        if ("1".equals(config.getMonitorTotalChromium()) && 
            config.getTotalChromiumThreshold() != null && 
            latestData.getTotalChromiumValue() != null) {
            
            if (latestData.getTotalChromiumValue().compareTo(config.getTotalChromiumThreshold()) > 0) {
                log.debug("总铬超标，企业ID: {}, 检测值: {}, 阈值: {}", 
                        config.getCompanyId(), latestData.getTotalChromiumValue(), config.getTotalChromiumThreshold());
                return false;
            }
        }
        
        // 检查总镍
        if ("1".equals(config.getMonitorTotalNickel()) && 
            config.getTotalNickelThreshold() != null && 
            latestData.getTotalNickelValue() != null) {
            
            if (latestData.getTotalNickelValue().compareTo(config.getTotalNickelThreshold()) > 0) {
                log.debug("总镍超标，企业ID: {}, 检测值: {}, 阈值: {}", 
                        config.getCompanyId(), latestData.getTotalNickelValue(), config.getTotalNickelThreshold());
                return false;
            }
        }
        
        return true; // 所有监测因子都正常
    }

    /**
     * 获取指定小时的数据值，优先取该小时整点的值，如果没有则取该小时内最近的值
     * @param hourData 该小时的数据列表
     * @param factorCode 监测因子编码
     * @param monitoringIdToFactorCodeMap 监测ID到因子编码的映射
     * @param hour 小时数
     * @param allHistoricalData 所有历史数据（用于查找最近值）
     * @return 数据值
     */
    private double getValueForHour(List<ParkOutletMonitoringLog> hourData, String factorCode, 
                                   Map<String, String> monitoringIdToFactorCodeMap, 
                                   int hour, List<ParkOutletMonitoringLog> allHistoricalData) {
        if (hourData == null || hourData.isEmpty()) {
            return 0.0;
        }

        // 首先尝试找到该小时整点的数据（分钟为0的数据）
        LocalDateTime targetHour = LocalDateTime.now().withHour(hour).withMinute(0).withSecond(0).withNano(0);
        
        Optional<ParkOutletMonitoringLog> exactTimeData = hourData.stream()
                .filter(log -> {
                    String logFactorCode = monitoringIdToFactorCodeMap.get(log.getMonitoringId());
                    return factorCode.equals(logFactorCode) && 
                           log.getLogTime().equals(targetHour);
                })
                .findFirst();

        if (exactTimeData.isPresent()) {
            return exactTimeData.get().getMonitoringValue() != null ? 
                   exactTimeData.get().getMonitoringValue().doubleValue() : 0.0;
        }

        // 如果没有整点数据，取该小时内最近的数据
        Optional<ParkOutletMonitoringLog> closestData = hourData.stream()
                .filter(log -> {
                    String logFactorCode = monitoringIdToFactorCodeMap.get(log.getMonitoringId());
                    return factorCode.equals(logFactorCode);
                })
                .min(Comparator.comparing(log -> Math.abs(
                        Duration.between(log.getLogTime(), targetHour).toMinutes())));

        if (closestData.isPresent()) {
            return closestData.get().getMonitoringValue() != null ? 
                   closestData.get().getMonitoringValue().doubleValue() : 0.0;
        }

        // 如果该小时内都没有数据，尝试从所有历史数据中找到最近的值
        Optional<ParkOutletMonitoringLog> nearestData = allHistoricalData.stream()
                .filter(log -> {
                    String logFactorCode = monitoringIdToFactorCodeMap.get(log.getMonitoringId());
                    return factorCode.equals(logFactorCode);
                })
                .min(Comparator.comparing(log -> Math.abs(
                        Duration.between(log.getLogTime(), targetHour).toMinutes())));

        return nearestData.map(log -> log.getMonitoringValue() != null ? 
                              log.getMonitoringValue().doubleValue() : 0.0)
                         .orElse(0.0);
    }
}
